﻿using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Text;
using System.Windows.Forms;
using System.Collections;
using DevExpress.Utils.Menu;
using DevExpress.XtraGrid.Views.Grid.ViewInfo;
using DevExpress.XtraBars;

namespace BSC_OTC_Management.Forms
{
    public partial class Form1 : Form
    {
        public Form1()
        {
            InitializeComponent();
        }

        #region KHAI BAO THAM SO, BIEN CHUNG

        Hashtable listTieuChi = new Hashtable();
        Hashtable list_CanTim = new Hashtable();
        Hashtable listDS_DK_TimKiem = new Hashtable();
        DataTable _tableView = new DataTable("SEARCHFLD");
        DataTable _tableTieuChi = new DataTable("SEARCHFLD");
        DataTable _tableHuyLenh = new DataTable("HUYLENH");
        DataTable table_bsc_vw_fun_info = new DataTable("table_bsc_vw_fun_info");
        static string v_StrSearchCode;

        string _operator = "";
        string _fieldtype = "";
        string _lookupcmdsql = "";
        string _BtnConfirmType = "";
        double _minAutoID = 0;
        string _orderID_Hist = "";
        List<string> _minAutoIDs = new List<string>();
        bool _minAutoIDs_check = false;
        int toadoX, toadoY, toadoX_CK, toadoY_CK;
        double _Quotetity = 0;

        Code.CL_Ultility cl_u = new Code.CL_Ultility();
        Code.StaticVariable _code = new Code.StaticVariable();
        string v_CompanyName, v_FundName, v_SubFunName, v_Custodycd, v_Side, V_Symbol, V_LimitQuantity, v_LimitPrice, V_unOrderQTY ,  v_Acctno, v_companyID;
        string btc_CompanyID, btc_Side, btc_Symbol;
        double btc_Price, btc_Quantity;
        Hashtable v_HtbSide = new Hashtable();
        DataTable dtb_tep2;
        DataTable dtb_tep;
        public DataTable v_dtbCompanyInFoFull;
        public DataTable v_dtbCompanyInFoFind;
        public DataTable v_dtbSubFundInfo;
        public DataTable v_dtbSide;
        #endregion

        #region CAC HAM TRONG FORM

        private float LamTron(double _e)
        {
            if (_e % 10000000 == 0)
            {
                return (float)_e * 1F;
            }
            else
            {
                int result = (int)(_e / 10000000 + 1);
                float aa = result * 10000000F;
                return aa;
            }
        }

        private float LamTronTuyTheoSan(double _e, string _san)
        {
            int chia = 100;
            switch (_san)
            {
                case "HOSE":
                    chia = 10;
                    break;
                default:
                    chia = 100;
                    break;
            }
            double le = _e % chia;
            if (le == 0)
            {
                return (float)_e * 1;
            }
            else
            {
                float aa = 0;
                switch (_san)
                {
                    case "HOSE":
                        if (le >= 5)
                        {
                            int result = (int)(_e / chia + 1);
                            aa = result * chia;
                        }
                        else
                        {
                            int result = (int)(_e / chia );
                            aa = result * chia;
                        }
                        break;
                    default:
                         if (le >= 50)
                        {
                            int result = (int)(_e / chia + 1);
                            aa = result * chia;
                        }
                        else
                        {
                            int result = (int)(_e / chia );
                            aa = result * chia;
                        }
                        break;
                }
                return aa;
            }
        }

        public string Dieu_kien_tim_kiem()
        {
            string V_sqlDK = "";
            string _sql_nang_cao = "";
            string _sql_basic = "";
            try
            {

                //--------------------------------------------------

                string v_strTieuChi = cbb_Tieu_chi_tim_kiem.Text.Trim();
                if (v_strTieuChi != "")
                {
                    foreach (DictionaryEntry item in this.listTieuChi)
                    {
                        if (item.Value.ToString() == v_strTieuChi)
                        {
                            _sql_basic = "AND  upper(" + item.Key + ") like '%" + cbb_Gia_tri_can_tim_basic.Text.ToUpper() + "%'";
                        }
                    }
                    //--------------------------------------------------------
                }

                if (checkBox_Tim_kiem_nang_cao.Checked)
                {
                    V_sqlDK = _sql_nang_cao + _sql_basic;
                }
                else
                {
                    V_sqlDK = _sql_basic;
                }
            }
            catch (Exception ex)
            {
                _code._services.UPDATE_LOG_FILE("ERR", Code.StaticVariable.userID, "Gen ", "Dieu_kien_tim_kiem", ex.ToString());
                Log_ung_dung(ex.ToString());
            }
            return V_sqlDK;
        }

        public void GetSelectedDataRows()
        {
            try
            {
                _tableHuyLenh = new DataTable("HUYLENH");
                //for (int i = 0; i < gridView5.SelectedRowsCount; i++)
                //{
                //    if (gridView5.GetSelectedRows()[i] >= 0)
                //        rows.Add(gridView5.GetDataRow(gridView5.GetSelectedRows()[i]));
                //}

                // tao columns
                foreach (DevExpress.XtraGrid.Columns.GridColumn item in gridView1.VisibleColumns)
                {
                    if (item.FieldName != "DX$CheckboxSelectorColumn")
                    {
                        _tableHuyLenh.Columns.Add(item.FieldName, item.ColumnType);
                    }
                }

                for (int i = 0; i < gridView1.SelectedRowsCount; i++)
                {
                    //CheckBox chk = gridView5.GetRowCellValue(i,gridView5.Columns[0]) as CheckBox; //row.Cells[0].Controls[0] as CheckBox;

                    if (gridView1.GetSelectedRows()[i] >= 0)
                    {
                        DataRow row = _tableHuyLenh.NewRow();
                        foreach (DevExpress.XtraGrid.Columns.GridColumn column in gridView1.VisibleColumns)
                        {
                            if (column.FieldName != "DX$CheckboxSelectorColumn")
                            {
                                try
                                {
                                    row[column.FieldName] = gridView1.GetRowCellValue(gridView1.GetSelectedRows()[i], column);
                                }
                                catch (Exception ex) { }
                            }
                        }
                        _tableHuyLenh.Rows.Add(row);
                    }
                }
            }
            catch (Exception ex)
            {
                _code._services.UPDATE_LOG_FILE("ERR", Code.StaticVariable.userID, "Lấy thông tin lệnh hủy", "GetSelectedDataRows", ex.ToString());
                Log_ung_dung(ex.ToString());
            }
        }

        void PatchSelection(DevExpress.XtraGrid.Views.Grid.GridView view)
        {
            try
            {
                int[] rows = view.GetSelectedRows();

                for (int i = 0; i < rows.Length; i++)
                {
                    Color color = (Color)view.GetRowCellValue(rows[i], "Color");
                    if (color == Color.Blue)
                        view.UnselectRow(rows[i]);
                }
            }
            catch (Exception ex)
            {
                _code._services.UPDATE_LOG_FILE("ERR", Code.StaticVariable.userID, "Hủy chọn", "PatchSelection", ex.ToString());
                Log_ung_dung(ex.ToString());
            }
        }

        private void FillTieuChi(string V_Searchcode)
        {
            try
            {
                //------Chuan bi cho tieu chi tim kiem-------------
                _tableView.Clear();
                _tableTieuChi.Clear();
                cbb_Tieu_chi_tim_kiem.Items.Clear();
                listTieuChi.Clear();

                // Lay danh sach the hien 
                _tableView = _code._services.GetViewBy_SearchCode(V_Searchcode);
                // Lay danh sach tim kiem
                _tableTieuChi = _code._services.GetPhepToanBy_SearchCode(V_Searchcode);
                foreach (DataRow row in _tableTieuChi.Rows)
                {
                    this.listTieuChi.Add(row["fieldcode"].ToString(), row["fieldname"].ToString());
                    this.cbb_Tieu_chi_tim_kiem.Items.Add(row["fieldname"].ToString());
                }
                try
                {

                }
                catch (Exception ex)
                {
                    MessageBox.Show(ex.ToString(), "ClearSelected - " + V_Searchcode);
                }
            }
            catch (Exception ex)
            {
                _code._services.UPDATE_LOG_FILE("ERR", Code.StaticVariable.userID, "Fill tiêu chí tìm kiếm", "FillTieuChi()", ex.ToString());
                Log_ung_dung(ex.ToString());
            }

        }

        public void Tim_kiem_theo_dieu_kien(Boolean V_FillTieuChi)
        {
            try
            {
                string v_TabPageName = tabControl_bao_cao.SelectedTab.Name;
                string _sql = Dieu_kien_tim_kiem();
                DataTable dtb_temp = new DataTable();

                switch (v_TabPageName)
                {
                    case "tabPage3_Lenh_duoi_flex":
                        //v_StrSearchCode = "OOD";
                        //if (V_FillTieuChi)
                        //{
                        //    FillTieuChi(v_StrSearchCode);
                        //}
                        ////---------------LOAD DU LIEU--------------------------
                        //dtb_temp = _code._services.SearchView_BySearchCode(v_StrSearchCode, _sql, "0001");
                        //gridControl1.DataSource = Change_DTB_ColumnName(dtb_temp, false); ;  
            
                            DataTable result = new DataTable("noname");
                            DataTable tableValue = new DataTable("value");

                            // tao 6 cot
                            tableValue.Columns.Add("P_TXDATE");
                            tableValue.Columns.Add("P_TLID");
                            tableValue.Columns.Add("P_CUSTODYCD");
                            tableValue.Columns.Add("P_AFACCTNO");
                            tableValue.Columns.Add("P_EXECTYPE");
                            tableValue.Columns.Add("P_SYMBOL");
                            tableValue.Columns.Add("P_FULLNAME");

                            // tao 1 Row chua gia tri
                            DataRow rowValue = tableValue.NewRow();
                            rowValue["P_TXDATE"] = "0";
                            rowValue["P_TLID"] = "1004";
                            rowValue["P_CUSTODYCD"] = "";
                            rowValue["P_FULLNAME"] = this.cbb_Company_Name.Text;
                            rowValue["P_AFACCTNO"] = "%%";
                            rowValue["P_EXECTYPE"] = "%%";
                            rowValue["P_SYMBOL"] = "%%";
                            tableValue.Rows.Add(rowValue);

                            // tao 1 Row chua kieu Du lieu cua cot ( int, string ?? ...)
                            DataRow rowDataType = tableValue.NewRow();
                            rowDataType["P_TXDATE"] = "T";
                            rowDataType["P_TLID"] = "T";
                            rowDataType["P_CUSTODYCD"] = "T";
                            rowDataType["P_FULLNAME"] = "T";
                            rowDataType["P_AFACCTNO"] = "T";
                            rowDataType["P_EXECTYPE"] = "T";
                            rowDataType["P_SYMBOL"] = "T";
                            tableValue.Rows.Add(rowDataType);

                            
                            result = _code._services.Excute_Store_By_ListString("fa_api.sp_get_order_by_careby", tableValue);
                            this.gridControl_SoLenhHOME.DataSource = null;
                            this.gridControl_SoLenhHOME.DataSource = this.ThayTenCot_SoLenhHome(result);;
                            
                        break;
                    case "tabPage4_lich_su_phan_bo_lenh":
                        v_StrSearchCode = "CF0078";
                        //if (V_FillTieuChi)
                        //{
                        //    FillTieuChi(v_StrSearchCode);
                        //}
                        //---------------LOAD DU LIEU--------------------------
                        dtb_temp = _code._services.SearchView_BySearchCode(v_StrSearchCode, _sql, "0001");
                        gridControl2_Lich_su_phan_bo_lenh.DataSource = Change_DTB_ColumnName(dtb_temp, false); ;
                        //-----------------------------------------------------
                        break;
                    case "tabPage_Theo_doi_ke_qua_khop_lenh":
                        v_StrSearchCode = "CF0077";
                        //if (V_FillTieuChi)
                        //{
                        //    FillTieuChi(v_StrSearchCode);
                        //}
                        //---------------LOAD DU LIEU--------------------------
                        dtb_temp = _code._services.SearchView_BySearchCode(v_StrSearchCode, _sql, "0001");
                        gridControl3_Theo_doi_kq_khop_lenh.DataSource = Change_DTB_ColumnName(dtb_temp, false); ;
                        //-----------------------------------------------------
                        break;
                    //case "tabPage4_Thong_tin_huy_lenh":
                    //    v_StrSearchCode = "FAOORDER";
                    //    //if (V_FillTieuChi)
                    //    //{
                    //    //    FillTieuChi(v_StrSearchCode);
                    //    //}

                    //    //---------------LOAD DU LIEU--------------------------

                    //    dtb_temp = this.EXECUTE_CMD_ORACLE("select * from FAOORDER");
                    //    //DataTable v_dtb_hl = Change_DTB_ColumnName(dtb_temp, true);
                    //    gridControl3_test.DataSource = dtb_temp;
                    //    DevExpress.XtraGrid.Views.Grid.GridView aa = gridControl3_test.FocusedView as DevExpress.XtraGrid.Views.Grid.GridView;
                    //    //_tableHuyLenh = dtb_temp.Clone();
                    //    //_tableHuyLenh.Clear();

                    //    //-----------------------------------------------------
                    //    break;
                    default:
                        Console.WriteLine("Default case");
                        break;
                }

                gridView1.BestFitColumns();
                gridView2.BestFitColumns();
                gridView3.BestFitColumns();
                //gridView5.BestFitColumns();

            }
            catch (Exception ex)
            {
                _code._services.UPDATE_LOG_FILE("ERR", Code.StaticVariable.userID, "Fill tiêu chí tìm kiếm", "Tim_kiem_theo_dieu_kien()", ex.ToString());
                Log_ung_dung(ex.ToString());
            }
        }

        private DataTable ThayTenCot_SoLenhHome(DataTable _tmp)
        {
            _tmp.Columns["custodycd"].Caption = "Số TK";
            _tmp.Columns["custodycd"].SetOrdinal(0);
            _tmp.Columns["symbol"].Caption = "Mã CK";
            _tmp.Columns["symbol"].SetOrdinal(1);
            _tmp.Columns["txtime"].Caption = "Thời gian";
            _tmp.Columns["txtime"].SetOrdinal(2);
            _tmp.Columns["exectype"].Caption = "Lệnh";
            _tmp.Columns["exectype"].SetOrdinal(3);
            _tmp.Columns["STATUS"].Caption = "Trạng thái";
            _tmp.Columns["STATUS"].SetOrdinal(4);
            _tmp.Columns["PRICETYPE"].Caption = "Kiểu lệnh";
            _tmp.Columns["PRICETYPE"].SetOrdinal(5);
            _tmp.Columns["VIA"].Caption = "Đặt từ";
            _tmp.Columns["VIA"].SetOrdinal(6);
            _tmp.Columns["TLNAME"].Caption = "Người đặt";
            _tmp.Columns["TLNAME"].SetOrdinal(7);
            _tmp.Columns["ORDERQTTY"].Caption = "KL đặt";
            _tmp.Columns["ORDERQTTY"].SetOrdinal(8);
            _tmp.Columns["QUOTEPRICE"].Caption = "Giá đặt";
            _tmp.Columns["QUOTEPRICE"].SetOrdinal(9);
            _tmp.Columns["EXECQTTY"].Caption = "KL khớp";
            _tmp.Columns["EXECQTTY"].SetOrdinal(10);
            _tmp.Columns["EXECPRICE"].Caption = "Giá khớp";
            _tmp.Columns["EXECPRICE"].SetOrdinal(11);
            _tmp.Columns["EXECAMT"].Caption = "Giá trị khớp";
            _tmp.Columns["EXECAMT"].SetOrdinal(12);
            _tmp.Columns["REMAINQTTY"].Caption = "Còn lại";
            _tmp.Columns["REMAINQTTY"].SetOrdinal(13);
            _tmp.Columns["REMAINAMT"].Caption = "Giá trị còn lại";
            _tmp.Columns["REMAINAMT"].SetOrdinal(14);
            _tmp.Columns["CANCELQTTY"].Caption = "Đã hủy";
            _tmp.Columns["CANCELQTTY"].SetOrdinal(15);
            _tmp.Columns["ADJUSTQTTY"].Caption = "Đã sửa";
            _tmp.Columns["ADJUSTQTTY"].SetOrdinal(16);
            _tmp.Columns["afacctno"].ColumnName = "CUSTID";
            _tmp.Columns["CUSTID"].SetOrdinal(17);
            _tmp.Columns["orderid"].ColumnName = "orgorderid";
            _tmp.Columns["orgorderid"].SetOrdinal(18);

            //_tmp.Columns["afacctno"].ColumnMapping = MappingType.Hidden;
            _tmp.Columns["txdate"].ColumnMapping = MappingType.Hidden;
            _tmp.Columns["desc_exectype"].ColumnMapping = MappingType.Hidden;
            //_tmp.Columns["orderid"].ColumnMapping = MappingType.Hidden;
            _tmp.Columns["iscancel"].ColumnMapping = MappingType.Hidden;
            _tmp.Columns["isadmend"].ColumnMapping = MappingType.Hidden;
            _tmp.Columns["lastChange"].ColumnMapping = MappingType.Hidden;
            _tmp.Columns["HOSEsession"].ColumnMapping = MappingType.Hidden;
            _tmp.Columns["TRADEPLACE"].ColumnMapping = MappingType.Hidden;
            _tmp.Columns["FOACCTNO"].ColumnMapping = MappingType.Hidden;
            _tmp.Columns["ISDISPOSAL"].ColumnMapping = MappingType.Hidden;
            _tmp.Columns["ORSTATUS"].ColumnMapping = MappingType.Hidden;
            _tmp.Columns["FEEDBACKMSG"].ColumnMapping = MappingType.Hidden;
            _tmp.Columns["ROOTORDERID"].ColumnMapping = MappingType.Hidden;
            _tmp.Columns["ORSTATUSVALUE"].ColumnMapping = MappingType.Hidden;
            _tmp.Columns["LIMITPRICE"].ColumnMapping = MappingType.Hidden;
            _tmp.Columns["QUOTEQTTY"].ColumnMapping = MappingType.Hidden;
            _tmp.Columns["CONFIRMED"].ColumnMapping = MappingType.Hidden;

          
            return _tmp;
        }

        private DataTable EXECUTE_PROCEDURE_ORACLE(string Proce_Name, string PV_COMPANYID, string PV_SIDE, string PV_SYMBOL, double PV_PRICE, double PV_QTTY)
        {
            try
            {
                DataTable result = new DataTable("noname");
                DataTable tableValue = new DataTable("value");

                // tao 5 cot

                tableValue.Columns.Add("PV_COMPANYID");
                tableValue.Columns.Add("PV_SIDE");
                tableValue.Columns.Add("PV_SYMBOL");
                tableValue.Columns.Add("PV_PRICE");
                tableValue.Columns.Add("PV_QTTY");

                // tao 1 Row chua gia tri
                DataRow rowValue = tableValue.NewRow();
                rowValue["PV_COMPANYID"] = PV_COMPANYID;
                rowValue["PV_SIDE"] = PV_SIDE;
                rowValue["PV_SYMBOL"] = PV_SYMBOL;
                rowValue["PV_PRICE"] = PV_PRICE;
                rowValue["PV_QTTY"] = PV_QTTY;
                tableValue.Rows.Add(rowValue);

                // tao 1 Row chua kieu Du lieu cua cot ( int, string ?? ...)
                DataRow rowDataType = tableValue.NewRow();
                rowDataType["PV_COMPANYID"] = "T";
                rowDataType["PV_SIDE"] = "T";
                rowDataType["PV_SYMBOL"] = "T";
                rowDataType["PV_PRICE"] = "N";
                rowDataType["PV_QTTY"] = "N";
                tableValue.Rows.Add(rowDataType);

                result = _code._services.Excute_Store_By_ListString("FA_API." + Proce_Name, tableValue);

                return result;
            }

            catch (Exception ex)
            {
                _code._services.UPDATE_LOG_FILE("ERR", Code.StaticVariable.userID, "Lỗi trong quá trình đặt lệnh", "EXECUTE_PROCEDURE_ORACLE", ex.ToString());
                Log_ung_dung(ex.ToString());
                return null;
            }
        }

        public DataTable EXECUTE_CMD_ORACLE(string cmd_SQL)
        {
            try
            {
                return _code._services.GetDatatable_BySQL(cmd_SQL);
            }
            catch (Exception ex)
            {
                //MessageBox.Show(ex.ToString(), " EXECUTE_CMD_ORACLE : " + cmd_SQL);
                _code._services.UPDATE_LOG_FILE("ERR", Code.StaticVariable.userID, cmd_SQL, "EXECUTE_CMD_ORACLE()", ex.ToString());
                Log_ung_dung(ex.ToString());
                return null;
            }
        }

        public void Set_value_to_Combobox(DataTable v_TBL, ComboBox cbb_name, string Collum_name, string v_strDK)
        {
            try
            {
                DataView dv = new DataView(v_TBL);
                dv.RowFilter = v_strDK;
                DataTable dbt_temp = new DataTable();
                dbt_temp = dv.ToTable();
                cbb_name.Items.Clear();
                for (int i = 0; i < dbt_temp.Rows.Count; i++)
                {
                    string v_item = dbt_temp.Rows[i][Collum_name].ToString();
                    if (cbb_name.Items.Contains(v_item) != true)
                    {
                        cbb_name.Items.Add(dbt_temp.Rows[i][Collum_name].ToString());
                        cbb_name.Text = dbt_temp.Rows[i][Collum_name].ToString();
                    }
                }
            }
            catch (Exception ex)
            {
                MessageBox.Show(ex.ToString());
            }
        }

        public void FILL_COLUMN_TO_COMBOBOX(DataTable v_TblName, ComboBox v_CbbName)
        {
            try
            {
                Int32 l = v_TblName.Columns.Count;
                v_CbbName.Items.Clear();

                for (int i = 0; i < l; i++)
                {
                    v_CbbName.Items.Add(v_TblName.Columns[i].ColumnName.ToString());
                }

            }
            catch (Exception ex)
            {
                MessageBox.Show(ex.ToString(), " FILL_COLUMN_TO_COMBOBOX ");

            }
        }

        public void CALCULATE_ALOCATE_ORDER(string v_type)
        {
            try
            {
                string v_company = cl_u.Get_key_HashTable(cl_u.v_HtbCompanyLIst, this.cbb_Company_Name.Text);
                this.v_companyID = v_company;
                string v_Side = cl_u.Get_key_HashTable(v_HtbSide, this.Cbb_MH1_Side_Loai_lenh.Text);
              
                if (v_company == "ALL")
                {
                    MessageBox.Show("Bạn chưa chọn công ty quản lý quỹ", "Thông báo");
                    this.cbb_Company_Name.Focus();
                    return;
                }

                if (v_Side == "ALL")
                {
                    MessageBox.Show("Bạn chưa chọn loại lệnh Mua/Bán ", "Thông báo");
                    this.Cbb_MH1_Side_Loai_lenh.Focus();
                    return;
                }

                string v_Symbol = this.cbb_MH1_Symbol_in.Text;
             
                Double v_Price, V_QTTY;
                try
                {
                    v_Price = double.Parse(this.cbb_MH1_gia_dat_du_kien.Text);
                }
                catch
                {
                    v_Price = 0;
                }

                try
                {
                    V_QTTY = double.Parse(this.cbb_MH1_KL_Du_kien.Text);
                }
                catch
                {
                    V_QTTY = 0;
                }

                if (V_QTTY == 0)
                {
                    return;
                }

                this.btc_Price =  v_Price;
                this.btc_Quantity = V_QTTY;
                this.btc_CompanyID = v_company;
                this.btc_Side = v_Side;
                this.btc_Symbol = v_Symbol;

                //dtb_tep = new DataTable();
                dtb_tep2 = new DataTable();
                //dtb_tep = EXECUTE_PROCEDURE_ORACLE("FAO002", v_company, v_Side, v_Symbol, v_Price, V_QTTY);
                dtb_tep2 = EXECUTE_PROCEDURE_ORACLE("FAO003", v_company, v_Side, v_Symbol, v_Price, V_QTTY);

                //if (v_type == "SAVE")
                //{
                //    if (this.cbbSolanKLToiDa.Text != "")
                //    {
                //        for (int i = 0; i < Convert.ToInt32(this.cbbSolanKLToiDa.Text); i++)
                //        {
                //           EXECUTE_PROCEDURE_ORACLE("FAO004", v_company, v_Side, v_Symbol, v_Price , V_QTTY);        
                //        }
                //    }
                //    else
                //    {
                //        EXECUTE_PROCEDURE_ORACLE("FAO004", v_company, v_Side, v_Symbol, v_Price, V_QTTY);
                //    }
                //}

                if (this.radioButton_PhanBo_Lenh.Checked)
                {
                    //double l_Count = dtb_tep.Rows.Count;
                    //double v_TongKL = 0;
                    //for (int i = 0; i < l_Count; i++)
                    //{
                    //    v_TongKL += double.Parse(dtb_tep.Rows[i]["QUOTEQTTY"].ToString());
                    //}

                    //if (v_TongKL == 0)
                    //{
                    //    return;
                    //}

                    //if (V_QTTY != v_TongKL)
                    //{
                    //    //  this.cbb_MH1_KL_Du_kien.Text = v_TongKL.ToString();
                    //}

                    //this.dataGridView2_lenh_Phan_bo.DataSource = null;
                    //this.dataGridView2_lenh_Phan_bo.DataSource = dtb_tep;
                }
                else
                {
                  
                    this.dataGridView2_lenh_Phan_bo.DataSource = null;
                    this.dataGridView2_lenh_Phan_bo.DataSource = dtb_tep2;
                }

            }
            catch (Exception ex)
            {
                _code._services.UPDATE_LOG_FILE("ERR", Code.StaticVariable.userID, "CALCULATE_ALOCATE_ORDER", "CALCULATE_ALOCATE_ORDER", ex.ToString());
                Log_ung_dung(ex.ToString());
            }
        }

        public void RECALCULATE_ALOCATE_ORDER(string v_type)
        {
            try
            {
                string v_company = cl_u.Get_key_HashTable(cl_u.v_HtbCompanyLIst, this.cbb_Company_Name.Text);
                string v_Side = cl_u.Get_key_HashTable(v_HtbSide, this.Cbb_MH1_Side_Loai_lenh.Text);

                if (v_company == "ALL")
                {
                    MessageBox.Show("Bạn chưa chọn công ty quản lý quỹ", "Thông báo");
                    this.cbb_Company_Name.Focus();
                    return;
                }

                if (v_Side == "ALL")
                {
                    MessageBox.Show("Bạn chưa chọn loại lệnh Mua/Bán ", "Thông báo");
                    this.Cbb_MH1_Side_Loai_lenh.Focus();
                    return;
                }

                string v_Symbol = this.cbb_MH1_Symbol_in.Text;
                Double v_Price, V_QTTY;
                try
                {
                    v_Price = double.Parse(this.cbb_MH1_gia_dat_du_kien.Text);
                }
                catch
                {
                    v_Price = 0;
                }


                if (v_Price * 1000 < double.Parse(this.lbl_Gia_san.Text) || v_Price > double.Parse(this.lbl_Gia_tran.Text))
                {
                    MessageBox.Show("Giá nhập phải nằm trong khoảng trần sàn", "Thông báo");
                    return;
                }

                try
                {
                    //V_QTTY = double.Parse(this.cbb_MH1_KL_Du_kien.Text);
                    V_QTTY = this._Quotetity;
                }
                catch
                {
                    V_QTTY = 0;
                }

                if (V_QTTY == 0)
                {
                    return;
                }

                DataTable tmpFao001 = (DataTable) this.dataGridView1.DataSource;
                dtb_tep = new DataTable();
                // tao columns
                dtb_tep.Columns.Add("PRICE");
                dtb_tep.Columns.Add("SUBFUNDNAME");
                dtb_tep.Columns.Add("QUOTEQTTY");
                dtb_tep.Columns.Add("SYMBOL");
                dtb_tep.Columns.Add("Tỷ lệ chia");
                //dtb_tep = EXECUTE_PROCEDURE_ORACLE("FAO002", v_company, v_Side, v_Symbol, v_Price, V_QTTY);
                double tongKL_UnorderedQty = 0;
                double tongKL = 0;
                // dtb_tep xu ly chia lenh tren FA
                foreach (DataRow row in tmpFao001.Rows)
                {
                    if (Convert.ToDouble(row["Limit Price ('000vnd)"]) >= v_Price)
                    {
                        tongKL_UnorderedQty += Convert.ToDouble(row["UNORDERED QUANTITY"]);
                    }
                    if (Convert.ToDouble(row["Amt"]) >= 0)
                    {
                        tongKL += Convert.ToDouble(row["Amt"]);
                    }
                }

                // kiem tra neu KL > KL chua dat thi bao loi
                if (V_QTTY > tongKL_UnorderedQty)
                {
                    MessageBox.Show("Kiểm tra lại giá đặt hoặc Khối lượng đặt phải nhỏ hơn khối lượng chưa chia!");
                    this.cbb_MH1_KL_Du_kien.Text = Convert.ToString( tongKL_UnorderedQty);
                    this.cbb_MH1_KL_Du_kien.Focus();
                    return;
                }

                double diem = V_QTTY / tongKL_UnorderedQty;

                foreach (DataRow row in tmpFao001.Rows)
                {
                    if (Convert.ToDouble(row["Limit Price ('000vnd)"]) >= v_Price)
                    {
                        DataRow rowNew = dtb_tep.NewRow();
                        rowNew["PRICE"] = Convert.ToString(v_Price);
                        rowNew["SUBFUNDNAME"] = Convert.ToString(row["SUBFUNDNAME"]);
                        double QUOTEQTTY = diem * Convert.ToDouble(row["UNORDERED QUANTITY"]);
                        QUOTEQTTY = this.LamTronTuyTheoSan(QUOTEQTTY, this.lbl_San_giao_dich.Text);
                        rowNew["QUOTEQTTY"] = Convert.ToString(QUOTEQTTY);
                        rowNew["SYMBOL"] = v_Symbol;

                        // xy ly cot ty le chia
                        double G5 = Convert.ToDouble(row["Amt"]) / tongKL;
                        double G7 = QUOTEQTTY / tongKL;
                        rowNew["Tỷ lệ chia"] = Convert.ToString(G7 / G5);

                        dtb_tep.Rows.Add(rowNew);
                    }
                }

                if (this.radioButton_PhanBo_Lenh.Checked)
                {
                    double l_Count = dtb_tep.Rows.Count;
                    double v_TongKL = 0;
                    for (int i = 0; i < l_Count; i++)
                    {
                        v_TongKL += double.Parse(dtb_tep.Rows[i]["QUOTEQTTY"].ToString());
                    }

                    if (v_TongKL == 0)
                    {
                        return;
                    }

                    if (V_QTTY != v_TongKL)
                    {
                        // this.cbb_MH1_KL_Du_kien.Text = v_TongKL.ToString();
                        // kiem tra lai xem co lon hon KL chua chia ko ?
                        if (v_TongKL > tongKL_UnorderedQty)
                        {
                            if (this.lbl_San_giao_dich.Text != "HOSE")
                            {
                                if (tongKL_UnorderedQty % 100 > 0)
                                {
                                    int result = (int)(tongKL_UnorderedQty / 100);
                                    tongKL_UnorderedQty = result * 100;
                                }
                            }
                            this.cbb_MH1_KL_Du_kien.Text = tongKL_UnorderedQty.ToString();
                        }
                        else
                        {
                            this.cbb_MH1_KL_Du_kien.Text = v_TongKL.ToString();
                        }
                      
                    }

                    this.dataGridView2_lenh_Phan_bo.DataSource = null;
                    this.dataGridView2_lenh_Phan_bo.DataSource = dtb_tep;
                }
                else
                {
                    dtb_tep2 = new DataTable();
                    dtb_tep2 = EXECUTE_PROCEDURE_ORACLE("FAO003", v_company, v_Side, v_Symbol, v_Price, V_QTTY);
                    this.dataGridView2_lenh_Phan_bo.DataSource = null;
                    this.dataGridView2_lenh_Phan_bo.DataSource = dtb_tep2;
                }
                this.LoadKL_ToiDa(tongKL_UnorderedQty, V_QTTY);
            }
            catch (Exception ex)
            {
                _code._services.UPDATE_LOG_FILE("ERR", Code.StaticVariable.userID, "RECALCULATE_ALOCATE_ORDER", "CALCULATE_ALOCATE_ORDER", ex.ToString());
                Log_ung_dung(ex.ToString());
            }
        }

        private void LoadKL_ToiDa(double _tongKL_UnorderedQty, double _V_QTTY)
        {
            this.cbbSolanKLToiDa.Items.Clear();
            int solan = Convert.ToInt32(_tongKL_UnorderedQty / _V_QTTY);
            this.lbl_KL_Toi_Da.Text = "KL còn lại: " + _tongKL_UnorderedQty.ToString();
            // show ra combobox
            for (int i = 1; i <= solan; i++)
            {
                this.cbbSolanKLToiDa.Items.Add(i);
            }
        }

        public void REFRESH_ORG_ORDER()
        {
            try
            {
                string v_company = cl_u.Get_key_HashTable(cl_u.v_HtbCompanyLIst, this.cbb_Company_Name.Text);
                string v_Side = cl_u.Get_key_HashTable(v_HtbSide, this.Cbb_MH1_Side_Loai_lenh.Text);
                if (v_Side == "B")
                {
                    panel1_mua_ban.BackColor = Color.FromArgb(167, 204, 240);
                }
                else if (v_Side == "S")
                {
                    panel1_mua_ban.BackColor = Color.FromArgb(245, 197, 217);

                }
                else
                {
                    panel1_mua_ban.BackColor = Color.DarkKhaki;
                }
                try
                {
                    this.v_Acctno = Convert.ToString(this.EXECUTE_CMD_ORACLE("select acctno from cfmast cf, afmast af " +
                                                        "where cf.custid = af.custid " +
                                                        " and cf.custodycd like '" + this.v_Custodycd + "'").Rows[0][0]);
                }
                catch (Exception ex) { }
                
                string v_Symbol = this.cbb_MH1_Symbol_in.Text;
                //this.V_Symbol = v_Symbol;
                string v_Symbol_temp = v_Symbol;

                if (v_Symbol_temp == cl_u.v_strTatCa)
                {
                    v_Symbol = "ALL";
                }

                DataTable tmp = new DataTable("noname");

                if (v_Symbol == "ALL")
                {
                    //tmp = this.EXECUTE_PROCEDURE_ORACLE("FAO001", "ALL", "ALL", "ALL", 0, 0);
                    tmp = this.KhoiTaoFao001();
                    tmp.Rows.Clear();
                    // lay danh sach cac ma CK dat trong ngay
                    DataTable tmpSymolInDays = this.EXECUTE_CMD_ORACLE("select DISTINCT(symbol) from bsc_fao_instruction_order where txdate=getcurrdate");
                    if (tmpSymolInDays.Rows.Count > 0)
                    {
                        foreach (DataRow row in tmpSymolInDays.Rows)
                        {
                            DataTable tmpSymbol = this.EXECUTE_PROCEDURE_ORACLE("FAO001", "ALL", "ALL", Convert.ToString(row["SYMBOL"]), 0, 0);
                            if (tmpSymbol.Rows.Count > 0)
                            {
                                foreach (DataRow rowChild in tmpSymbol.Rows)
                                {
                                    tmp.ImportRow(rowChild);
                                }
                            }
                        }
                    }
                }
                else
                {
                    tmp = EXECUTE_PROCEDURE_ORACLE("FAO001", v_company, v_Side, v_Symbol, 0, 0);
                }
               
                tmp = this.GetAveragePrice(tmp);
                this.dataGridView1.DataSource = tmp;
                this.dataGridView1.Columns["SUBFUNDNAME"].Width = 170;
                this.dataGridView1.Columns["insorderid"].Width = 50;
                this.cbb_Loai_lenh.SelectedIndex = 2;
            }
            catch (Exception ex)
            {
                _code._services.UPDATE_LOG_FILE("ERR", Code.StaticVariable.userID, "Load lại danh sách lệnh chỉ thị", "REFRESH_ORG_ORDER", ex.ToString());
                Log_ung_dung(ex.ToString());
            }
        }

        // xu ly cot Average Price
        private DataTable GetAveragePrice(DataTable _tmp)
        {
            foreach (DataRow row in _tmp.Rows)
            {
                DataTable tmpPhanBoLenh = this.EXECUTE_CMD_ORACLE("select * from bsc_fao_allocated_order a, iod " +
                                                                    " where a.txdate=getcurrdate " +
                                                                    " and insorderid='" + Convert.ToString(row["insorderid"]) + "'" +
                                                                    " and iod.orgorderid = a. flexorderid");
                double tongKL = 0, tongGiaTri = 0;
                
                foreach (DataRow rowPhanbo in tmpPhanBoLenh.Rows)
                {
                    tongKL += Convert.ToDouble(rowPhanbo["matchqtty"]);
                    tongGiaTri += Convert.ToDouble(rowPhanbo["matchqtty"]) * Convert.ToDouble(rowPhanbo["matchprice"]);
                }
                double giaKhopTB = tongGiaTri / tongKL;
                try
                {
                    row["Average Price"] = Convert.ToString(giaKhopTB);
                }
                catch (Exception ex)
                {
                    row["Average Price"] = "0";
                }
            }
            return _tmp;
        }

        // xu ly cot Gia khop trung binh toan Thi truong
        private DataTable GetVWAP(DataTable _tmp)
        {
            foreach (DataRow row in _tmp.Rows)
            {
                DataTable tmpPhanBoLenh = this.EXECUTE_CMD_ORACLE("select * from stock_info where SYMBOL like '"+Convert.ToString(row["SYMBOL"])+"'");
                if (tmpPhanBoLenh.Rows.Count>0)
                {
                    row["VWAP"] = Convert.ToString("averageprice") ;
                }
            }
            return _tmp;
        }

        public void load_thong_tin_chung_khoan(string v_symbolName)
        {
            try
            {
                if (v_symbolName == cl_u.v_strTatCa)
                {
                    return;
                }
                string v_gia = cl_u.Get_value_HashTable(cl_u.v_HtbSymbol, v_symbolName);

                if (v_gia.Trim() != "")
                {
                    string[] v_arrGia = v_gia.Split('|');

                    if (v_arrGia.Length != 0)
                    {
                        this.lbl_MCK.Text = v_symbolName;
                        switch (v_arrGia[0].ToString())
                        {
                            case "001":
                                lbl_San_giao_dich.Text = "HOSE";
                                break;
                            case "002":
                                lbl_San_giao_dich.Text = "HNX";
                                break;
                            case "005":
                                lbl_San_giao_dich.Text = "UPCOM";
                                break;
                            default:
                                break;
                        }
                        //lbl_San_giao_dich.Text = v_arrGia[0].ToString();
                        lbl_Gia_san.Text = v_arrGia[1].ToString();
                        lbl_Tham_chieu.Text = v_arrGia[2].ToString();
                        lbl_Gia_tran.Text = v_arrGia[3].ToString();
                    };
                }
                else
                {
                    this.lbl_MCK.Text = "";
                    lbl_San_giao_dich.Text = "";
                    lbl_Gia_san.Text = "";
                    lbl_Tham_chieu.Text = "";
                    lbl_Gia_tran.Text = "";
                }
            }
            catch (Exception ex)
            {
                _code._services.UPDATE_LOG_FILE("ERR", Code.StaticVariable.userID, "load_thong_tin_chung_khoan", "load_thong_tin_chung_khoan", ex.ToString());
                Log_ung_dung(ex.ToString());
            }
        }

        private DataTable Change_DTB_ColumnName(DataTable v_DataTable, Boolean v_AddCheckColumn)
        {
            try
            {
                foreach (DataColumn column in v_DataTable.Columns)
                {
                    foreach (DataRow row in _tableView.Rows)
                    {
                        if (row["FIELDCODE"].ToString().ToUpper() == column.ColumnName.ToUpper())
                        {
                            v_DataTable.Columns[column.ColumnName].ColumnName = row["fieldname"].ToString(); ;
                        }
                    }
                }

                if (v_AddCheckColumn)
                {
                    v_DataTable.Columns.Add("true", typeof(System.Int32));
                    foreach (DataRow row in v_DataTable.Rows)
                    {
                        //need to set value to NewColumn column
                        row["true"] = false;   // or set it to some other value
                    }
                }
                return v_DataTable;
            }
            catch (Exception ex)
            {
                _code._services.UPDATE_LOG_FILE("ERR", Code.StaticVariable.userID, "Thay thông tin tên cột khai báo dưới Database", "Change_DTB_ColumnName()", ex.ToString());
                Log_ung_dung(ex.ToString());
            }
            return null;
        }

        public void Log_ung_dung(String V_StrErr)
        {
            richTextBox_Log.Text += "\n";
            richTextBox_Log.Text += "====================" + cl_u.Current_DATE("dd/mm/yyyy hh:pp:ss") + "================";
            richTextBox_Log.Text += "\n";
            richTextBox_Log.Text += V_StrErr.ToString();
            richTextBox_Log.Text += "\n";
            richTextBox_Log.Text += "\n";
            richTextBox_Log.Text += "\n";
            this.btn_Thong_bao_Canh_bao.Visible = true;
            this.btn_Thong_bao_OK.Visible = false;
        }

        private void CreateTabsTTKhopLenh()
        {
            //// có bao nhiêu Quỹ con, tạo ra bấy nhiêu tab
            //foreach (DataRow row in v_dtbCompanyInFoFull.Rows)
            //{
            //    TabPage _page = new TabPage(row["subfundname"].ToString());
            //    _page.AccessibleDescription = row["subfundid"].ToString();
            //    this.tabThongTinKL_Child.TabPages.Add(_page);
            //}

            //// Mỗi tab có 1 gridview tương ứng
            //foreach (TabPage item in this.tabThongTinKL_Child.TabPages)
            //{
            //    DevExpress.XtraGrid.GridControl _gridTTKL = new DevExpress.XtraGrid.GridControl();
            //    _gridTTKL.DataSource = this.EXECUTE_CMD_ORACLE("select symbol , trim(TO_CHAR( executedquantity, '999,999,999,999,999,999,999')) as executedquantity ,limitqty, avg_matchprice, limitprice/1000 limitprice from bsc_vw_instrucsorder_info where subfundid='" + item.AccessibleDescription + "'");
            //    _gridTTKL.Dock = DockStyle.Fill;
            //    item.Controls.Add(_gridTTKL);
            //}
        }

        private DataTable KhoiTaoFao001()
        {
            DataTable result = new DataTable("fao001");
            result.Columns.Add("SUBFUNDNAME");
            result.Columns.Add("CUSTODYCD");
            result.Columns.Add("Status");
            result.Columns.Add("B/S");
            result.Columns.Add("Ticker");
            result.Columns.Add("Amt");
            result.Columns.Add("Limit Price ('000vnd)");
            result.Columns.Add("Filled");
            result.Columns.Add("% Filled");
            result.Columns.Add("Average Price");
            result.Columns.Add("VWAP");
            result.Columns.Add("UNORDERED QUANTITY");
            result.Columns.Add("Pending Quantity");
            result.Columns.Add("Order value");
            result.Columns.Add("insorderid");
            return result;
        }

        private DataTable LoadStoreFao001(string _symbol)
        {
            DataTable result = this.KhoiTaoFao001();
            if (_symbol == "Tất cả")
            {
                DataTable tbltemp1 = this.EXECUTE_CMD_ORACLE("select * from bsc_fao_instruction_order i, bsc_vw_fun_info f "+
                " where txdate=getcurrdate "+
                " and i.subfundid=f.subfundid");
                foreach (DataRow row in tbltemp1.Rows)
                {
                    DataRow rowtmp = result.NewRow();
                    rowtmp["SUBFUNDNAME"] = Convert.ToString(row["SUBFUNDNAME"]);
                    rowtmp["CUSTODYCD"] = Convert.ToString(row["CUSTODYCD"]);
                }
            }
            return result;
        }

        private void LoadTabPhongVT()
        {
            try
            {
                // load danh sach khach hang 
                this.table_bsc_vw_fun_info = this.EXECUTE_CMD_ORACLE("select * from bsc_vw_fun_info");
                this.cbb_phongvt_sotk.DataSource = this.EXECUTE_CMD_ORACLE("select custodycd from bsc_fao_funds_info");
                this.cbb_phongvt_sotk.DisplayMember = "custodycd";

                // load tien nong cac the loai

                //load lenh chi thi

                string v_company = cl_u.Get_key_HashTable(cl_u.v_HtbCompanyLIst, this.cbb_Company_Name.Text);
                string v_Side = cl_u.Get_key_HashTable(v_HtbSide, this.Cbb_MH1_Side_Loai_lenh.Text);
                string v_Symbol = this.cbb_MH1_Symbol_in.Text;
                string v_Symbol_temp = v_Symbol;
                if (v_Symbol_temp == cl_u.v_strTatCa)
                {
                    v_Symbol = "ALL";
                }
                //DataTable _tmp = this.EXECUTE_PROCEDURE_ORACLE("FAO001", "ALL", "ALL", "ALL", 0, 0);
                DataTable _tmp = this.LoadStoreFao001("");
                _tmp.Rows.Clear();

                // lay danh sach cac ma CK dat trong ngay
                DataTable tmpSymolInDays = this.EXECUTE_CMD_ORACLE("select DISTINCT(symbol) from bsc_fao_instruction_order where txdate=getcurrdate");
                if (tmpSymolInDays.Rows.Count > 0)
                {
                    foreach (DataRow row in tmpSymolInDays.Rows)
                    {
                        DataTable tmpSymbol = this.EXECUTE_PROCEDURE_ORACLE("FAO001", "ALL", "ALL", Convert.ToString(row["SYMBOL"]), 0, 0);
                        if (tmpSymbol.Rows.Count > 0)
                        {
                            foreach (DataRow rowChild in tmpSymbol.Rows)
                            {
                                _tmp.ImportRow(rowChild);
                            }
                        }
                    }
                }


                _tmp = this.GetAveragePrice(_tmp);
                this.gridview_LenhChiThi_TQ.DataSource = _tmp;

                // them dau * ben canh Symbol khi lenh co chinh sua
                for (int i = 0; i < _tmp.Rows.Count; i++)
                {
                    DataTable _tmpchild = this.EXECUTE_CMD_ORACLE("select * from bsc_fao_instruction_order_hist where insorderid='" + Convert.ToString(_tmp.Rows[i]["insorderid"]) + "'");
                    if (_tmpchild.Rows.Count > 0)
                    {
                        this.gridview_LenhChiThi_TQ.Rows[i].Cells["TICKER"].Value = this.gridview_LenhChiThi_TQ.Rows[i].Cells["TICKER"].Value.ToString() + " *";
                    }
                }

                // them dau . vao number
                this.gridview_LenhChiThi_TQ.Columns["Amt"].ValueType = typeof(System.Double);
                this.gridview_LenhChiThi_TQ.Columns["Amt"].DefaultCellStyle.Format = "N0";
                this.gridview_LenhChiThi_TQ.Columns["UNORDERED QUANTITY"].ValueType = typeof(System.Double);
                this.gridview_LenhChiThi_TQ.Columns["UNORDERED QUANTITY"].DefaultCellStyle.Format = "N0";
                this.gridview_LenhChiThi_TQ.Columns["Order value"].ValueType = typeof(System.Double);
                this.gridview_LenhChiThi_TQ.Columns["Order value"].DefaultCellStyle.Format = "N0";

                // thu gon width 1 so cot
                this.gridview_LenhChiThi_TQ.Columns["Limit Price ('000vnd)"].Width = 50;
                this.gridview_LenhChiThi_TQ.Columns["Ticker"].Width = 50;
                this.gridview_LenhChiThi_TQ.Columns["B/S"].Width = 50;
                this.gridview_LenhChiThi_TQ.Columns["Status"].Width = 50;
                this.gridview_LenhChiThi_TQ.Columns["Amt"].Width = 60;
                this.gridview_LenhChiThi_TQ.Columns["insorderid"].Width = 65;

                // boi dam cot Limit Price
                this.gridview_LenhChiThi_TQ.Columns["Limit Price ('000vnd)"].DefaultCellStyle.Font = new Font(this.gridview_LenhChiThi_TQ.Font, FontStyle.Bold);

                // justify 1 so cot sang ben phai
                this.gridview_LenhChiThi_TQ.Columns["Amt"].DefaultCellStyle.Alignment = DataGridViewContentAlignment.MiddleRight;
                this.gridview_LenhChiThi_TQ.Columns["UNORDERED QUANTITY"].DefaultCellStyle.Alignment = DataGridViewContentAlignment.MiddleRight;
                this.gridview_LenhChiThi_TQ.Columns["Order value"].DefaultCellStyle.Alignment = DataGridViewContentAlignment.MiddleRight;
                this.gridview_LenhChiThi_TQ.Columns["Limit Price ('000vnd)"].DefaultCellStyle.Alignment = DataGridViewContentAlignment.MiddleRight;
                this.gridview_LenhChiThi_TQ.Columns["Filled"].DefaultCellStyle.Alignment = DataGridViewContentAlignment.MiddleRight;
                this.gridview_LenhChiThi_TQ.Columns["Average Price"].DefaultCellStyle.Alignment = DataGridViewContentAlignment.MiddleRight;
                this.gridview_LenhChiThi_TQ.Columns["vwap"].DefaultCellStyle.Alignment = DataGridViewContentAlignment.MiddleRight;
                this.gridview_LenhChiThi_TQ.Columns["Pending Quantity"].DefaultCellStyle.Alignment = DataGridViewContentAlignment.MiddleRight;
            }
            catch ( Exception ex)
            {
                
            }
          
        }

        private void LoadTTTienNongVaCK()
        {
            //Load so Dt quy
            DataTable tablePhone = this.EXECUTE_CMD_ORACLE("select phone from bsc_fao_funds_info where custodycd like '" + cbb_phongvt_sotk.Text + "'");
            if (tablePhone.Rows.Count > 0)
            {
                this.lblPhoneQuy.Text = Convert.ToString(tablePhone.Rows[0]["phone"].ToString());
            }
            // tao table Lich Su lenh Moi nhat
            DataTable tableOrderHistNew = this.EXECUTE_CMD_ORACLE("select * from bsc_fao_instruction_order_hist where autoid in ( " +
                                                                    "select max(autoid) from bsc_fao_instruction_order_hist fa " +
                                                                    "where txdate=getcurrdate " +
                                                                    "group by insorderid)");

            // tao column
            DataTable tableTienNong = new DataTable("tableTienNong");
            DataTable tableChungKhoan = new DataTable("tableChungKhoan");
            tableTienNong.Columns.Add("Nội dung");
            tableChungKhoan.Columns.Add("Nội dung");
            tableTienNong.Columns.Add("Số lưu ký - " + this.cbb_phongvt_sotk.Text);
            tableChungKhoan.Columns.Add("Số lưu ký - " + this.cbb_phongvt_sotk.Text);
            foreach (DataRow row in table_bsc_vw_fun_info.Rows)
            {
                if (row["custodycd"].ToString() == this.cbb_phongvt_sotk.Text)
                {
                    tableTienNong.Columns.Add(Convert.ToString(row["subfundname"]));
                    tableChungKhoan.Columns.Add(Convert.ToString(row["subfundname"]));
                }
            }

            // tao row 1
            DataTable table_bsc_fao_instruction_order = this.EXECUTE_CMD_ORACLE("select * from bsc_fao_instruction_order i, bsc_vw_fun_info vf " +
                                                                                "where txdate = getcurrdate " +
                                                                                "and i.subfundid = vf.subfundid " +
                                                                                "and vf.custodycd = '" + this.cbb_phongvt_sotk.Text + "' " +
                                                                                "and deltd='N'");
            DataTable tableSymbol = this.EXECUTE_CMD_ORACLE("select distinct(symbol) from bsc_fao_instruction_order where txdate =getcurrdate");
            //Hien thi tien 
            double tongtien = 0;
            double tongtienHist = 0;
            foreach (DataRow row in table_bsc_fao_instruction_order.Rows)
            {
                if (Convert.ToString(row["SIDE"]) == "B")
                {
                    tongtien += Convert.ToDouble(row["limitqty"]) * Convert.ToDouble(row["limitprice"]);
                    bool check = false;
                    foreach (DataRow rowHist in tableOrderHistNew.Rows)
                    {
                        if (Convert.ToString(row["insorderid"]) == Convert.ToString(rowHist["insorderid"]))
                        {
                            check = true;
                            tongtienHist += Convert.ToDouble(rowHist["limitqty"]) * Convert.ToDouble(rowHist["limitprice"]);
                            break;
                        }
                    }
                    if (check == false)
                    {
                        // kiem tra neu ko co ma CK do thi thoi

                        tongtienHist += Convert.ToDouble(row["limitqty"]) * Convert.ToDouble(row["limitprice"]);
                    }
                }
            }
            // them phi 0.02 %
            tongtienHist = tongtienHist * 1.002;
            tongtien = tongtien * 1.002;
            double tongtienChenh = this.LamTron(tongtien - tongtienHist);
            tongtien = this.LamTron(tongtien);
            DataRow rowFirst = tableTienNong.NewRow();
            rowFirst[0] = "Tiền";
            if (tongtienChenh == 0)
            {
                rowFirst[1] = String.Format("{0:#,##0}", tongtien);
            }
            if (tongtienChenh > 0)
            {
                rowFirst[1] = String.Format("{0:#,##0}", tongtien) + " (+" + String.Format("{0:#,##0}", tongtienChenh) + ")";
            }
            if (tongtienChenh < 0)
            {
                rowFirst[1] = String.Format("{0:#,##0}", tongtien) + " (" + String.Format("{0:#,##0}", tongtienChenh) + ")";
            }

            for (int i = 2; i < tableTienNong.Columns.Count; i++)
            {
                double tienQuy = 0;
                double tienQuyHist = 0;
                foreach (DataRow row in table_bsc_fao_instruction_order.Rows)
                {
                    if (Convert.ToString(row["SIDE"]) == "B")
                    {
                        if (Convert.ToString(row["subfundname"]) == Convert.ToString(tableTienNong.Columns[i].ColumnName))
                        {
                            tienQuy += Convert.ToDouble(row["limitqty"]) * Convert.ToDouble(row["limitprice"]);
                            bool check = false;
                            foreach (DataRow rowHist in tableOrderHistNew.Rows)
                            {
                                if (Convert.ToString(row["insorderid"]) == Convert.ToString(rowHist["insorderid"]))
                                {
                                    check = true;
                                    tienQuyHist += Convert.ToDouble(rowHist["limitqty"]) * Convert.ToDouble(rowHist["limitprice"]);
                                    break;
                                }
                            }
                            if (check == false)
                            {
                                tienQuyHist += Convert.ToDouble(row["limitqty"]) * Convert.ToDouble(row["limitprice"]);
                            }
                        }
                    }
                }
                tienQuy = tienQuy * 1.002;
                tienQuyHist = tienQuyHist * 1.002;
                double tienQuyChenh = this.LamTron( tienQuy - tienQuyHist);
                tienQuy = this.LamTron(tienQuy);
                if (tienQuyChenh == 0)
                {
                    rowFirst[i] = String.Format("{0:#,##0}", tienQuy);
                }
                if (tienQuyChenh > 0)
                {
                    rowFirst[i] = String.Format("{0:#,##0}", tienQuy) + " (+" + String.Format("{0:#,##0}", tienQuyChenh) + ")";
                }
                if (tienQuyChenh < 0)
                {
                    rowFirst[i] = String.Format("{0:#,##0}", tienQuy) + " (" + String.Format("{0:#,##0}", tienQuyChenh) + ")";
                }
            }
            try
            {
                if (rowFirst[1].ToString() != "0" ) 
                 {
                     tableTienNong.Rows.Add(rowFirst);
                 }
            }
            catch (Exception ex) { }
           

            #region Hien thi Khoi Luong Lenh voi lenh Buy
            foreach (DataRow rowSymbol in tableSymbol.Rows)
            {
                double Symbol_qty = 0;
                double Symbol_qtysmall = 0;
                double qtt_chenhTong = 0;
                DataRow newRow = tableTienNong.NewRow();
                foreach (DataRow rowData in table_bsc_fao_instruction_order.Rows)
                {
                    if (Convert.ToString(rowData["symbol"]) == Convert.ToString(rowSymbol["symbol"]) && Convert.ToString(rowData["SIDE"]) == "B")
                    {
                        Symbol_qty += Convert.ToDouble(rowData["limitqty"]);
                        for (int i = 2; i < tableTienNong.Columns.Count; i++)
                        {
                            if (Convert.ToString(rowData["subfundname"]) == Convert.ToString(tableTienNong.Columns[i].ColumnName))
                            {
                                Symbol_qtysmall = Convert.ToDouble(rowData["limitqty"]);
                                double qty_chenh = 0;
                                // kiem tra xem neu co lich su lenh thi hien thi gia tri chenh lenh
                                foreach (DataRow rowHist in tableOrderHistNew.Rows)
                                {
                                    if (Convert.ToString(rowHist["insorderid"]) == Convert.ToString(rowData["insorderid"]))
                                    {
                                        qty_chenh = Symbol_qtysmall - Convert.ToDouble(rowHist["limitqty"]);
                                        qtt_chenhTong += qty_chenh;
                                    }
                                }
                                if (qty_chenh == 0)
                                {
                                    newRow[i] = String.Format("{0:#,##0}", Symbol_qtysmall);
                                }
                                if (qty_chenh > 0)
                                {
                                    newRow[i] = String.Format("{0:#,##0}", Symbol_qtysmall) + " (+" + String.Format("{0:#,##0}", qty_chenh) + ")";
                                }
                                if (qty_chenh < 0)
                                {
                                    newRow[i] = String.Format("{0:#,##0}", Symbol_qtysmall) + " (" + String.Format("{0:#,##0}", qty_chenh) + ")";
                                }
                                break;
                            }
                        }
                    }
                }

                newRow[0] = Convert.ToString(rowSymbol["symbol"]);
                if (qtt_chenhTong == 0)
                {
                    newRow[1] = String.Format("{0:#,##0}", Symbol_qty);
                }
                if (qtt_chenhTong > 0)
                {
                    newRow[1] = String.Format("{0:#,##0}", Symbol_qty) + " (+" + String.Format("{0:#,##0}", qtt_chenhTong) + ")";
                }
                if (qtt_chenhTong < 0)
                {
                    newRow[1] = String.Format("{0:#,##0}", Symbol_qty) + " (" + String.Format("{0:#,##0}", qtt_chenhTong) + ")" ;
                }

                try
                {
                    if (newRow[1].ToString() == "0" && newRow[2].ToString() == "") { }
                    else
                    {
                        tableTienNong.Rows.Add(newRow);
                    }
                }
                catch (Exception ex)
                {
                    tableTienNong.Rows.Add(newRow);
                }
            }
            #endregion

            #region Hien thi Khoi Luong Lenh voi lenh Sell
            foreach (DataRow rowSymbol in tableSymbol.Rows)
            {
                double Symbol_qty = 0;
                double Symbol_qtysmall = 0;
                double qtt_chenhTong = 0;
                DataRow newRow = tableChungKhoan.NewRow();
                foreach (DataRow rowData in table_bsc_fao_instruction_order.Rows)
                {
                    if (Convert.ToString(rowData["symbol"]) == Convert.ToString(rowSymbol["symbol"]) && Convert.ToString(rowData["SIDE"]) == "S")
                    {
                        Symbol_qty += Convert.ToDouble(rowData["limitqty"]);
                        for (int i = 2; i < tableTienNong.Columns.Count; i++)
                        {
                            if (Convert.ToString(rowData["subfundname"]) == Convert.ToString(tableTienNong.Columns[i].ColumnName))
                            {
                                Symbol_qtysmall = Convert.ToDouble(rowData["limitqty"]);
                                double qty_chenh = 0;
                                // kiem tra xem neu co lich su lenh thi hien thi gia tri chenh lenh
                                foreach (DataRow rowHist in tableOrderHistNew.Rows)
                                {
                                    if (Convert.ToString(rowHist["insorderid"]) == Convert.ToString(rowData["insorderid"]))
                                    {
                                        qty_chenh = Symbol_qtysmall - Convert.ToDouble(rowHist["limitqty"]);
                                        qtt_chenhTong += qty_chenh;
                                    }
                                }
                                if (qty_chenh == 0)
                                {
                                    newRow[i] = String.Format("{0:#,##0}", Symbol_qtysmall);
                                }
                                if (qty_chenh > 0)
                                {
                                    newRow[i] = String.Format("{0:#,##0}", Symbol_qtysmall) + " (+" + String.Format("{0:#,##0}", qty_chenh) + ")";
                                }
                                if (qty_chenh < 0)
                                {
                                    newRow[i] = String.Format("{0:#,##0}", Symbol_qtysmall) + " (" + String.Format("{0:#,##0}", qty_chenh) + ")";
                                }
                                break;
                            }
                        }
                    }
                }

                newRow[0] = Convert.ToString(rowSymbol["symbol"]);
                if (qtt_chenhTong == 0)
                {
                    newRow[1] = String.Format("{0:#,##0}", Symbol_qty);
                }
                if (qtt_chenhTong > 0)
                {
                    newRow[1] = String.Format("{0:#,##0}", Symbol_qty) + " (+" + String.Format("{0:#,##0}", qtt_chenhTong) + ")";
                }
                if (qtt_chenhTong < 0)
                {
                    newRow[1] = String.Format("{0:#,##0}", Symbol_qty) + " (" + String.Format("{0:#,##0}", qtt_chenhTong) + ")" + ")";
                }

                try
                {
                    if (newRow[1].ToString() == "0" && newRow[2].ToString() == "") { }
                    else
                    {
                        tableChungKhoan.Rows.Add(newRow);
                    }
                }
                catch (Exception ex)
                {
                    tableChungKhoan.Rows.Add(newRow);
                }
            }
            #endregion

            this.gridviewTien_Phongvt.DataSource = tableTienNong;
            this.gridviewCK_Phongvt.DataSource = tableChungKhoan;

            // bold dong dau tien
            try
            {
                this.gridviewTien_Phongvt.Rows[0].Cells[1].Style.Font = new Font(gridviewTien_Phongvt.Font, FontStyle.Bold);
                this.gridviewCK_Phongvt.Rows[0].Cells[1].Style.Font = new Font(gridviewTien_Phongvt.Font, FontStyle.Bold);
            }
            catch (Exception ex) { }

            // tu dong co gian 2 grid view TIEN va CK
            this.gridviewTien_Phongvt.Width = this.Width / 2 - 30;
            this.gridviewCK_Phongvt.Width = this.Width / 2 - 30;

            // tu dong co gian theo cot
            for (int i = 0; i < this.gridviewTien_Phongvt.Columns.Count; i++)
            {
                this.gridviewTien_Phongvt.Columns[i].AutoSizeMode = DataGridViewAutoSizeColumnMode.AllCells;
                this.gridviewCK_Phongvt.Columns[i].AutoSizeMode = DataGridViewAutoSizeColumnMode.AllCells;
            }

           // disable sort Column
            for (int i = 0; i < this.gridviewTien_Phongvt.Columns.Count; i++)
            {
                this.gridviewTien_Phongvt.Columns[i].SortMode = DataGridViewColumnSortMode.NotSortable;
            }
            for (int i = 0; i < this.gridviewCK_Phongvt.Columns.Count; i++)
            {
                this.gridviewCK_Phongvt.Columns[i].SortMode = DataGridViewColumnSortMode.NotSortable;
            }

            // xu ly de hien thi nhung thay doi da confirm voi ngan hang luu ky
            try
            {
                // kiem tra xem duoi bsc_tbl_confirm_nhlk co du lieu chua, neu chua thi insert ban ghi moi
                foreach (DataGridViewColumn column in this.gridviewTien_Phongvt.Columns)
                {
                    if (column.Index>1)
                    {
                        foreach (DataRow row in v_dtbCompanyInFoFull.Rows)
                        {
                            if (Convert.ToString( row["subfundname"]) == column.HeaderText)
                            {
                                string subfundid = Convert.ToString(row["subfundid"]);
                                DataTable tmp = this.EXECUTE_CMD_ORACLE("select * from bsc_tbl_confirm_nhlk where txdate=getcurrdate and subfundid='" + subfundid + "'");
                                // neu ko co KQ, tao 1 row chua gia tri cho subfundid + so tien
                                if (tmp.Rows.Count==0)
                                {
                                    string tien = Convert.ToString(this.gridviewTien_Phongvt.Rows[0].Cells[column.Index].Value);
                                    this.EXECUTE_CMD_ORACLE("insert into bsc_tbl_confirm_nhlk(tien,checktien,txdate,subfundid) values ('" + tien + "','0',getcurrdate,'" + subfundid + "')");
                                    this.gridviewTien_Phongvt.Rows[0].Cells[column.Index].Style.BackColor = Color.Yellow;
                                }
                                else
                                {
                                    // neu co , kiem tra neu Chjeck =0 thi hien mau do
                                    if (Convert.ToString(tmp.Rows[0]["checktien"]) == "0")
                                    {
                                        this.gridviewTien_Phongvt.Rows[0].Cells[column.Index].Style.BackColor = Color.Yellow;
                                    }

                                    // neu  = 1, thi kiem tra xem tien = nhau hay ko, neu ko thi chung to da thay doi, update tien
                                    string tienNew = Convert.ToString( this.gridviewTien_Phongvt.Rows[0].Cells[column.Index].Value);
                                    if (Convert.ToString(tmp.Rows[0]["checktien"]) == "1" &&
                                        Convert.ToString(tmp.Rows[0]["tien"]) != tienNew)
                                    {
                                        this.EXECUTE_CMD_ORACLE("update bsc_tbl_confirm_nhlk set checktien='0',tien='"+tienNew+"' where txdate=getcurrdate and subfundid='" + subfundid + "'");
                                        this.gridviewTien_Phongvt.Rows[0].Cells[column.Index].Style.BackColor = Color.Yellow;   
                                    }
                                }
                            }
                        }
                    }
                }
            }
            catch (Exception ex) { }

            // kiem tra bang bsc_tbl_ck_confirm_nhlk
            try
            {
                foreach (DataGridViewColumn column in this.gridviewCK_Phongvt.Columns)
                {
                    if (column.Index>1)
                    {
                        string subfundid = "";
                        foreach (DataRow row in v_dtbCompanyInFoFull.Rows)
                        {
                            if (Convert.ToString(row["subfundname"]) == column.HeaderText)
                            {
                                subfundid = Convert.ToString(row["subfundid"]);
                            }
                        }
                        int i=0;
                        foreach (DataGridViewRow row in this.gridviewCK_Phongvt.Rows)
                        {
                            // kiem tra xem co du lieu hay chua, neu chua thi insert vao
                            string symbol = Convert.ToString(row.Cells[0].Value);
                            string quantity = Convert.ToString(row.Cells[column.Index].Value);
                            DataTable tmp = this.EXECUTE_CMD_ORACLE("select * from bsc_tbl_ck_confirm_nhlk where  "+
                                                                      " symbol like '"+symbol+"' and"+
                                                                      " subfundid like '"+subfundid+"' and " +
                                                                      " txdate=getcurrdate ");
                            if (tmp.Rows.Count==0)
                            {
                                // insert vao bang
                                this.EXECUTE_CMD_ORACLE("insert into bsc_tbl_ck_confirm_nhlk(symbol,txdate,check_ck,subfundid,quantty) "+
                                                        " values('" + symbol + "' , getcurrdate, '0', '" + subfundid + "' , '" + quantity + "')");
                                this.gridviewCK_Phongvt.Rows[i].Cells[column.Index].Style.BackColor = Color.Yellow;
                            }
                            else
                            {
                                // neu co ban ghi kiem tra xem cot quantty co giong nhau ko
                                if (Convert.ToString(tmp.Rows[0]["quantty"]) != quantity)
                                {
                                    this.EXECUTE_CMD_ORACLE("update bsc_tbl_ck_confirm_nhlk set quantty='" + quantity + "' where subfundid='"+subfundid+"' "+
                                                            " and txdate=getcurrdate and symbol='" + symbol + "'");
                                    this.gridviewCK_Phongvt.Rows[i].Cells[column.Index].Style.BackColor = Color.Yellow;
                                }
                                else
                                {
                                    if (Convert.ToString(tmp.Rows[0]["check_ck"]) == "0")
                                    {
                                         this.gridviewCK_Phongvt.Rows[i].Cells[column.Index].Style.BackColor = Color.Yellow;
                                    }
                                }
                            }
                            i++;
                        }
                    }
                }
            }
            catch (Exception ex) { }
        }
        #endregion

        #region CAC SU KIEN TREN CONTROLS

        private void gridviewCK_Phongvt_MouseDown(object sender, MouseEventArgs e)
        {
            if (e.Button == MouseButtons.Right)
            {
                var hti = gridviewCK_Phongvt.HitTest(e.X, e.Y);
                this.toadoX_CK = hti.ColumnIndex;
                this.toadoY_CK = hti.RowIndex;
            }
        }

        private void btnVCF3001_Click(object sender, EventArgs e)
        {
            DateTime fromDate, toDate;
            if (DateTime.TryParse(this.mtbFromDate.Text, out fromDate) == false)
            {
                MessageBox.Show("Kiểm tra lại từ ngày");
                return;
            }
            if (DateTime.TryParse(this.mtbToDate.Text, out toDate) == false)
            {
                MessageBox.Show("Kiểm tra lại đến ngày");
                return;
            }
            if (this.cbbAcctno.Text == "")
            {
                MessageBox.Show("Vui lòng chọn số tiểu khoản");
                return;
            }

            DataTable result = new DataTable("noname");
            DataTable tableValue = new DataTable("value");

            // tao 5 cot

            tableValue.Columns.Add("F_DATE");
            tableValue.Columns.Add("T_DATE");
            tableValue.Columns.Add("PV_CUSTODYCD");
            tableValue.Columns.Add("PV_AFACCTNO");
            tableValue.Columns.Add("PV_BORS");

            // tao 1 Row chua gia tri
            DataRow rowValue = tableValue.NewRow();
            rowValue["F_DATE"] = this.mtbFromDate.Text;
            rowValue["T_DATE"] = this.mtbToDate.Text;
            rowValue["PV_CUSTODYCD"] = this.mtbCustodycd.Text;
            rowValue["PV_AFACCTNO"] = this.cbbAcctno.Text;
            rowValue["PV_BORS"] = this.mtbSide.Text;
            tableValue.Rows.Add(rowValue);

            // tao 1 Row chua kieu Du lieu cua cot ( int, string ?? ...)
            DataRow rowDataType = tableValue.NewRow();
            rowDataType["F_DATE"] = "D";
            rowDataType["T_DATE"] = "D";
            rowDataType["PV_CUSTODYCD"] = "T";
            rowDataType["PV_AFACCTNO"] = "T";
            rowDataType["PV_BORS"] = "T";
            tableValue.Rows.Add(rowDataType);

            result = _code._services.Excute_Store_By_ListString("cf3001", tableValue);
            if (result.Rows.Count > 0)
            {
                this.dgvVCF3001.DataSource = result;
            }
            else
            {
                MessageBox.Show("Báo cáo không có dữ liệu!");
            }
        }

        private void mtbCustodycd_Leave(object sender, EventArgs e)
        {
            DataTable tmp = this.EXECUTE_CMD_ORACLE("select * from cfmast cf, afmast af " +
                                                    " where cf.custid = af.custid " +
                                                    " and cf.custodycd like '" + this.mtbCustodycd.Text + "'");
            if (tmp.Rows.Count > 0)
            {
                this.cbbAcctno.Text = "";
                this.cbbAcctno.Items.Clear();
                foreach (DataRow row in tmp.Rows)
                {
                    this.cbbAcctno.Items.Add(Convert.ToString(row["acctno"]));
                }
                if (this.cbbAcctno.Items.Count > 0)
                {
                    this.cbbAcctno.SelectedIndex = 0;
                }
            }
        }

        // xac nhan CK voi NH LK
        private void toolStripMenuItem1_Click(object sender, EventArgs e)
        {
            if (this.toadoX_CK >1 )
            {
                string symbol = this.gridviewCK_Phongvt.Rows[this.toadoY_CK].Cells[0].Value.ToString();
                string subfundid = "";
                foreach (DataRow row in this.v_dtbCompanyInFoFull.Rows)
                {
                    if (Convert.ToString(row["subfundname"]) == this.gridviewCK_Phongvt.Columns[this.toadoX_CK].HeaderText)
                    {
                        subfundid = Convert.ToString(row["subfundid"]);
                    }
                }
                this.EXECUTE_CMD_ORACLE("update bsc_tbl_ck_confirm_nhlk set check_ck='1' where txdate=getcurrdate and subfundid='" + subfundid + "' and symbol='"+symbol+"'");
                LoadTTTienNongVaCK();
            }
        }

        private void cbb_SubFundName_TextChanged(object sender, EventArgs e)
        {
            Set_value_to_Combobox(v_dtbCompanyInFoFull, this.cbb_FundName, "fundname", "subfundname='" + this.cbb_SubFundName.Text + "'");
            Set_value_to_Combobox(v_dtbCompanyInFoFull, this.cbb_Custodycd, "custodycd", "subfundname='" + this.cbb_SubFundName.Text + "'");
        }

        private void cbb_SymBol_TextChanged(object sender, EventArgs e)
        {
            try
            {
                string v_gia = cl_u.Get_value_HashTable(cl_u.v_HtbSymbol, this.cbb_SymBol.Text);

                if (v_gia.Trim() != "")
                {
                    string[] v_arrGia = v_gia.Split('|');

                    if (v_arrGia.Length != 0)
                    {
                        switch (v_arrGia[0].ToString())
                        {
                            case "001":
                                lbl_San_giao_dich_TQ.Text = "HOSE";
                                break;
                            case "002":
                                lbl_San_giao_dich_TQ.Text = "HNX";
                                break;
                            case "005":
                                lbl_San_giao_dich_TQ.Text = "UPCOM";
                                break;
                            default:
                                break;
                        }
                        lbl_Gia_san_TQ.Text = v_arrGia[1].ToString();
                        lbl_Tham_chieu_TQ.Text = v_arrGia[2].ToString();
                        lbl_Gia_tran_TQ.Text = v_arrGia[3].ToString();
                    };
                }
                else
                {
                    lbl_San_giao_dich_TQ.Text = "";
                    lbl_Gia_san_TQ.Text = "";
                    lbl_Tham_chieu_TQ.Text = "";
                    lbl_Gia_tran_TQ.Text = "";
                }

            }
            catch (Exception ex)
            { }
        }

        private void btnBuy_Click(object sender, EventArgs e)
        {
            // doi giao dien
            this.cbb_SymBol.Text = "";
            this.cbb_LimitQuantty.Text = "";
            this.cbb_LimitPrice.Text = "";
            this._BtnConfirmType = "B";
            this.cbb_SubFundName.SelectedIndex = cbb_SubFundName.Items.Count - 1;
            this.panel2.BackColor = Color.FromArgb(192, 255, 192);
        }

        private void btnSell_Click(object sender, EventArgs e)
        {
            // doi giao dien
            this.cbb_SymBol.Text = "";
            this.cbb_LimitQuantty.Text = "";
            this.cbb_LimitPrice.Text = "";
            this._BtnConfirmType = "S";
            this.cbb_SubFundName.SelectedIndex = cbb_SubFundName.Items.Count - 1;
            this.panel2.BackColor = Color.FromArgb(255, 128, 128);
        }

        private void Order_Click(string _side, string v_FormType)
        {
            try
            {
                double pv_LimitPrice, pv_limitqty;
                double pv_gia_san, pv_Gia_tran;
                string pv_symbol, pv_Side, v_Cmd;
                pv_Side = _side;
                pv_symbol = this.cbb_SymBol.Text;

                if (pv_Side == "")
                {
                    MessageBox.Show("Vui lòng chọn lệnh là mua hay bán!");
                    return;
                }

                if (pv_symbol.Trim() == "")
                {
                    MessageBox.Show("[SYMBOL]-Chưa chọn mã chứng khoán! ", "Thông báo");
                    this.cbb_SymBol.Focus();
                    return;
                }

                try
                {
                    pv_limitqty = Double.Parse(this.cbb_LimitQuantty.Text);
                    if (pv_limitqty <= 0)
                    {
                        MessageBox.Show("Khối lượng không hợp lệ", "Thông báo");
                        this.cbb_LimitQuantty.Focus();
                        return;
                    }
                }
                catch
                {
                    MessageBox.Show("Khối lượng không hợp lệ", "Thông báo");
                    this.cbb_LimitQuantty.Focus();
                    return;
                }

                try
                {
                    pv_LimitPrice = Double.Parse(this.cbb_LimitPrice.Text) * 1000;
                    pv_gia_san = double.Parse(this.lbl_Gia_san_TQ.Text);
                    pv_Gia_tran = double.Parse(this.lbl_Gia_tran_TQ.Text);

                    if (pv_LimitPrice < pv_gia_san || pv_LimitPrice > pv_Gia_tran)
                    {
                        MessageBox.Show("Giá nhập phải nằm trong khoảng trần sàn", "Thông báo");
                        return;
                    }
                }
                catch
                {
                    MessageBox.Show("Giá không hợp lệ", "Thông báo");
                    this.cbb_LimitPrice.Focus();
                    return;
                }

                if (cbb_Custodycd.Text.Trim() == "")
                {
                    MessageBox.Show("Số tài khoản không hợp lệ", "Thông báo");
                    this.cbb_Custodycd.Focus();
                    return;
                }

                // Don vi gia 10000
                //pv_LimitPrice = pv_LimitPrice * 1000;

                switch (v_FormType)
                {
                    case "ADD":
                        string V_subFundID = cl_u.Get_key_HashTable(cl_u.v_HtbSubfund, this.cbb_SubFundName.Text);
                        if (V_subFundID.Trim() == "")
                        {
                            MessageBox.Show("Kiểm tra lại thông tin quỹ", "Thông báo");
                            this.cbb_SubFundName.Focus();
                            return;
                        }
                        //this.Text = "Thêm mới lệnh chỉ thị";

                        string v_cmdCheck = "Select deltd From bsc_fao_instruction_order where SUBFUNDID ='" + V_subFundID + "' and SIDE='" + pv_Side + "' and SYMBOL='" + pv_symbol + "' and txdate =getcurrdate";
                        DataTable dtb_check = _code._services.GetDatatable_BySQL(v_cmdCheck);

                        if (dtb_check.Rows.Count > 0)
                        {
                            string v_strDelt = dtb_check.Rows[0]["deltd"].ToString();
                            if (v_strDelt == "N")
                            {
                                MessageBox.Show("Quỹ đã có lệnh tương tự trong hệ thống", "Thông báo");
                                return;
                            }
                            else if (v_strDelt == "Y")
                            {
                                DialogResult rs = MessageBox.Show("Quỹ đã có lệnh tương ứng [ở trạng thái xóa] trong hệ thống, bạn có muốn kích hoạt lại ?", "Thông báo", MessageBoxButtons.YesNo, MessageBoxIcon.Question, MessageBoxDefaultButton.Button2);
                                if (rs == DialogResult.No)
                                {
                                    return;
                                }
                                else
                                {
                                    v_Cmd = @"Update bsc_fao_instruction_order set  deltd='N'  , limitqty =" + pv_limitqty + "  , limitprice = " + pv_LimitPrice +
                                  " Where 0=0 " +
                                  " And txdate =getcurrdate " +
                                  " And symbol ='" + this.cbb_SymBol.Text + "'" +
                                  " And side ='" + _side + "'" +
                                  " And subfundid = (Select subfundid From bsc_fao_subfunds_info where subfundname='" + this.cbb_SubFundName.Text + "') ";
                                    _code._services.Excute_DB(v_Cmd);
                                    MessageBox.Show("Kích hoạt lại lệnh chỉ thị thành công", "Thông báo");
                                    LoadTabPhongVT();
                                    LoadTTTienNongVaCK();
                                    break;
                                }

                            }
                        }

                        v_Cmd = @"INSERT INTO bsc_fao_instruction_order (INSORDERID,SUBFUNDID,SIDE,SYMBOL,LIMITQTY,LIMITPRICE,STATUS,DELTD,TLID,TXDATE,LAST_CHANGE,DESCRIPTION)" +
                                      "VALUES(seq_insorderid.nextval ," + V_subFundID + ",'" + pv_Side + "','" + pv_symbol + "'," + pv_limitqty + "," + pv_LimitPrice + ",'A','N','1024',getcurrdate,sysdate,NULL)";

                        if (_code._services.Excute_DB(v_Cmd) == true)
                        {
                            MessageBox.Show("Thêm mới lệnh chỉ thị thành công", "Thông báo");
                            LoadTabPhongVT();
                            LoadTTTienNongVaCK();
                          
                        }
                        else
                        {
                            MessageBox.Show("Thêm mới lệnh chỉ thị không thành công", "Thông báo");
                        }

                        break;
                }
            }
            catch (Exception ex)
            {
                MessageBox.Show(ex.ToString());
            }
        }

        private void dataGridView1_RowPrePaint(object sender, DataGridViewRowPrePaintEventArgs e)
        {
            try
            {
                if (dataGridView1.Rows[e.RowIndex].Cells["B/S"].Value.ToString() == "B")
                {
                    dataGridView1.Rows[e.RowIndex].DefaultCellStyle.ForeColor = Color.Green;
                }
                else
                {
                    dataGridView1.Rows[e.RowIndex].DefaultCellStyle.ForeColor = Color.Red;
                }
                dataGridView1.Rows[e.RowIndex].DefaultCellStyle.BackColor = Color.White;
            }
            catch (Exception ex) { }
        }

        private void gridview_LenhChiThi_TQ_RowPrePaint(object sender, DataGridViewRowPrePaintEventArgs e)
        {
            try
            {
                if (gridview_LenhChiThi_TQ.Rows[e.RowIndex].Cells["B/S"].Value.ToString() == "B")
                {
                    gridview_LenhChiThi_TQ.Rows[e.RowIndex].DefaultCellStyle.ForeColor = Color.Green;
                }
                else
                {
                    gridview_LenhChiThi_TQ.Rows[e.RowIndex].DefaultCellStyle.ForeColor = Color.Red;
                }
                gridview_LenhChiThi_TQ.Rows[e.RowIndex].DefaultCellStyle.BackColor = Color.White;
            }
            catch (Exception ex) { }
        }

        private void tabControl_Main_SelectedIndexChanged(object sender, EventArgs e)
        {
            //if (this.tabControl_Main.SelectedTab == this.tabThongTinKL)
            //{
            //    this.CreateTabsTTKhopLenh();
            //}
            //else
            //{
            //    this.tabThongTinKL_Child.TabPages.Clear();
            //}

            if (this.tabControl_Main.SelectedTab == this.tabTongQuan)
            {
                this.LoadTabPhongVT();
            }

            if (this.tabControl_Main.SelectedTab == this.tabVCF3001)
            {
                this.LoadTabVCF3001();
            }
        }

        private void LoadTabVCF3001()
        {
            this.mtbFromDate.Text = DateTime.Now.ToShortDateString();
            this.mtbToDate.Text = DateTime.Now.ToShortDateString();
        }

        private void cbb_MH1_gia_dat_du_kien_Leave(object sender, EventArgs e)
        {
            RECALCULATE_ALOCATE_ORDER("CAL");
        }

        private void gridView5_MouseDown_1(object sender, MouseEventArgs e)
        {
            if (e.Button == System.Windows.Forms.MouseButtons.Right)
            {
                GridHitInfo hi = gridView1.CalcHitInfo(Cursor.Position);
                contextMenuStrip2.Show(Cursor.Position);
            }
        }

        private void btn_Thong_bao_Canh_bao_Click(object sender, EventArgs e)
        {
            try
            {
                tabControl_Main.SelectedIndex = 1;
                this.btn_Thong_bao_Canh_bao.Visible = false;
                this.btn_Thong_bao_OK.Visible = true;
            }
            catch { }
        }

        private void dataGridView1_DoubleClick(object sender, EventArgs e)
        {
            try
            {
                int v_strRowIndex = this.dataGridView1.CurrentCell.RowIndex;
                //string v_strCompanyName = this.dataGridView1["COMPANYNAME", v_strRowIndex].Value.ToString();
                string v_strSIDE = this.dataGridView1["B/S", v_strRowIndex].Value.ToString();

                if (v_strSIDE == "B")
                {

                    v_strSIDE = "Mua";
                }
                else
                {
                    v_strSIDE = "Bán";

                }
                string v_strSYMBOL = this.dataGridView1["Ticker", v_strRowIndex].Value.ToString();

                //this.cbb_Company_Name.Text = v_strCompanyName;
                this.Cbb_MH1_Side_Loai_lenh.Text = v_strSIDE;
                this.cbb_MH1_Symbol_in.Text = v_strSYMBOL;
                this.cbb_MH1_KL_Du_kien.Text = "1000";
                this.cbb_MH1_gia_dat_du_kien.Focus();
                this.load_thong_tin_chung_khoan(cbb_MH1_Symbol_in.Text);
                this.Tim_kiem_theo_dieu_kien(false);
            }
            catch (Exception ex)
            {
                _code._services.UPDATE_LOG_FILE("ERR", Code.StaticVariable.userID, "HuyLenhToolStripMenuItem_Click", "HuyLenhToolStripMenuItem_Click", ex.ToString());
                Log_ung_dung(ex.ToString());
            }
        }

        private void ToolStripMenuItem3_Lam_moi_so_lenh_chi_thi_Click(object sender, EventArgs e)
        {
            try
            {
                //this.cbb_Company_Name.Text = cl_u.v_strTatCa;
                this.Cbb_MH1_Side_Loai_lenh.Text = cl_u.v_strTatCa;
                this.cbb_MH1_Symbol_in.Text = cl_u.v_strTatCa;
            }
            catch (Exception ex)
            {
                _code._services.UPDATE_LOG_FILE("ERR", Code.StaticVariable.userID, "HuyLenhToolStripMenuItem_Click", "HuyLenhToolStripMenuItem_Click", ex.ToString());
                Log_ung_dung(ex.ToString());
            }
        }

        private void cbb_MH1_KL_Du_kien_Leave(object sender, EventArgs e)
        {
            try
            {
                this._Quotetity = Convert.ToDouble(cbb_MH1_KL_Du_kien.Text);
                RECALCULATE_ALOCATE_ORDER("CAL");
            }
            catch (Exception ex)
            {
                MessageBox.Show("Bạn chưa gõ số lượng");
            }
        }

        private void btn_tim_kiem_Click(object sender, EventArgs e)
        {
            Tim_kiem_theo_dieu_kien(false);
        }

        private void cbb_Gia_tri_can_tim_basic_TextChanged(object sender, EventArgs e)
        {
            Tim_kiem_theo_dieu_kien(false);
        }

        private void gridView5_SelectionChanged(object sender, DevExpress.Data.SelectionChangedEventArgs e)
        {
            GetSelectedDataRows();
        }

        private void btn_them_lenh_chi_thi_Click(object sender, EventArgs e)
        {
            try
            {
                if (Code.StaticVariable.V_BoolLOG)
                { _code._services.UPDATE_LOG_FILE("LOG", Code.StaticVariable.userID, "Bấm nút thêm lệnh chỉ thị", "btn_them_lenh_chi_thi_Click()", ""); }

                Frm_Orgorder_manage frm_orgOrder = new Frm_Orgorder_manage(cl_u.v_HtbSubfund, cl_u.v_HtbSymbol, cl_u.v_dtbSymbolInfo);
                frm_orgOrder.Get_FormType = "ADD";
                frm_orgOrder.Get_dtbCompanyInfo = v_dtbCompanyInFoFull;
                frm_orgOrder.ShowDialog();
                REFRESH_ORG_ORDER();
            }
            catch
            {
                REFRESH_ORG_ORDER();
            }
        }

        private void btn_Lam_moi_lenh_chi_thi_Click(object sender, EventArgs e)
        {
            REFRESH_ORG_ORDER();
        }

        private void btn_DatlenhvaoFlex_Click(object sender, EventArgs e)
        {
            try
            {
                //CALCULATE_ALOCATE_ORDER("CAL");
                string v_strLoaiLenh = cbb_Loai_lenh.Text;
                int v_nSumQTTY0;
                double v_nPrice;
                try
                {
                    v_nSumQTTY0 = Int32.Parse(this.cbb_MH1_KL_Du_kien.Text);
                    if (v_nSumQTTY0 <= 0)
                    {
                        MessageBox.Show("Khối lượng phân bổ không hợp lệ", "Thông báo");
                        return;
                    }
                }
                catch
                {
                    MessageBox.Show("Khối lượng phân bổ không hợp lệ", "Thông báo");
                    this.cbb_MH1_KL_Du_kien.Focus();
                    return;
                };

                if (v_strLoaiLenh.Trim() == "")
                {
                    MessageBox.Show("Bạn chưa chọn loại lệnh", "Thông báo");
                    this.cbb_Loai_lenh.Focus();
                    return;
                }

                if (dtb_tep2 == null)
                {
                    MessageBox.Show("Không tìm thấy thông tin lệnh đặt", "Thông báo");
                    return;
                }
                else if (dtb_tep2.Rows.Count == 0)
                {
                    MessageBox.Show("Không tìm thấy thông tin lệnh đặt", "Thông báo");
                    return;
                }

                // Kiểm tra lô đặt lệnh
                // Kiem tra lai thong tin gia , tradelot theo bang lenh
                int l = dtb_tep.Rows.Count;

                for (int i = 0; i < l; i++)
                {

                    if (i == 0)
                    {   // Lay lai thong tin chung khoan
                        load_thong_tin_chung_khoan(dtb_tep.Rows[0]["Symbol"].ToString());
                    }
                    Int32 v_intKLDat = Int32.Parse(dtb_tep.Rows[i]["QUOTEQTTY"].ToString().Replace(",", ""));

                    if (v_intKLDat == 0)
                    {
                        MessageBox.Show("Lệnh phải có khối lượng đặt lớn hơn không", "Thông báo");
                        return;
                    }

                    if (lbl_San_giao_dich.Text.ToUpper() == "HOSE" && v_intKLDat % 10 != 0)
                    {
                        MessageBox.Show("[Hose:10] - Lô giao dịch không hợp lệ !", "Thông báo");
                        return;
                    }

                    if (lbl_San_giao_dich.Text.ToUpper() == "HNX" && v_intKLDat % 100 != 0)
                    {
                        MessageBox.Show("[HNX:100] - Lô giao dịch không hợp lệ !", "Thông báo");
                        return;
                    }

                    if (lbl_San_giao_dich.Text.ToUpper() == "UPCOM" && v_intKLDat % 100 != 0)
                    {
                        MessageBox.Show("[HNX:100] - Lô giao dịch không hợp lệ !", "Thông báo");
                        return;
                    }
                }
                try
                {
                    v_nPrice = double.Parse(this.cbb_MH1_gia_dat_du_kien.Text) * 1000;

                    if (v_nPrice <= 0)
                    {
                        MessageBox.Show("Giá phân bổ lệnh không hợp lệ", "Thông báo");
                        return;
                    }

                    //----------------------------------------------------
                    try
                    {

                        Double pv_gia_san = double.Parse(this.lbl_Gia_san.Text);
                        Double pv_Gia_tran = double.Parse(this.lbl_Gia_tran.Text);

                        if (v_nPrice < pv_gia_san || v_nPrice > pv_Gia_tran)
                        {
                            MessageBox.Show("Giá nhập phải nằm trong khoảng trần sàn", "Thông báo");
                            this.cbb_MH1_gia_dat_du_kien.Focus();
                            return;
                        }
                    }
                    catch
                    {
                        MessageBox.Show("Giá không hợp lệ", "Thông báo");
                        return;
                    }
                }
                catch
                {
                    MessageBox.Show("Giá phân bổ lệnh không hợp lệ", "Thông báo");
                    this.cbb_MH1_gia_dat_du_kien.Focus();
                    return;
                };
                Frm_PlaceOrder frm_PLaceOD = new Frm_PlaceOrder();
                frm_PLaceOD.Get_LenhFlex = dtb_tep2;
                frm_PLaceOD.Get_loaiLenh = cbb_Loai_lenh.Text;
                frm_PLaceOD.Companyid = this.v_companyID;
                frm_PLaceOD.QuantityGoc = v_nSumQTTY0.ToString();
                if (cbbSolanKLToiDa.Text=="")
                {
                    frm_PLaceOD.Solanlap = 1;
                }
                else
                {
                    frm_PLaceOD.Solanlap = Convert.ToInt32(cbbSolanKLToiDa.Text);
                }
                frm_PLaceOD.ShowDialog();
                if (cl_u.Get_PlaceOrder_Status == true)
                {
                    CALCULATE_ALOCATE_ORDER("SAVE");
                    radioButton_PhanBo_Lenh.Checked = true;
                    this.REFRESH_ORG_ORDER();
                    this.cbb_MH1_gia_dat_du_kien.Text = "";
                    this.cbb_MH1_KL_Du_kien.Text = "";
                    this.dataGridView2_lenh_Phan_bo.DataSource = null;
                    //this.panel1_mua_ban.BackColor = Color.DarkKhaki;
                    this.lbl_MCK.Text = "";
                    lbl_Gia_san.Text = "";
                    lbl_Tham_chieu.Text = "";
                    lbl_Gia_tran.Text = "";
                    this.cbbSolanKLToiDa.Items.Clear();
                }
            }
            catch (Exception ex)
            {
                REFRESH_ORG_ORDER();
                Tim_kiem_theo_dieu_kien(true);
                _code._services.UPDATE_LOG_FILE("ERR", Code.StaticVariable.userID, "Bấm nút đặt lệnh vào Flex", "btn_DatlenhvaoFlex_Click", ex.ToString());
                Log_ung_dung(ex.ToString());

            }
        }

        private void checkBox_Tim_kiem_nang_cao_CheckedChanged(object sender, EventArgs e)
        {
            if (checkBox_Tim_kiem_nang_cao.Checked == true)
            {
                this.splitContainer3.SplitterDistance = 260;
            }
            else
            {
                this.splitContainer3.SplitterDistance = 0;
            }
        }

        private void tabControl_bao_cao_SelectedIndexChanged(object sender, EventArgs e)
        {
            try
            {
                Tim_kiem_theo_dieu_kien(true);
            }
            catch { }

        }

        private void Form1_Load(object sender, EventArgs e)
        {
            try
            {
                v_dtbCompanyInFoFull = EXECUTE_CMD_ORACLE("Select * From bsc_vw_fun_info");
                cl_u.v_dtbSymbolInfo = EXECUTE_CMD_ORACLE("Select symbol KeyName ,tradeplace || '|' || floorprice|| '|' || avgprice  || '|' || ceilingprice  KeyValue From bsc_vw_symbol_info");
                v_dtbCompanyInFoFind = EXECUTE_CMD_ORACLE("Select companyid KeyName , fullname KeyValue From bsc_fao_company_info");
                v_dtbSubFundInfo = EXECUTE_CMD_ORACLE("Select subfundid KeyName , subfundname KeyValue   From bsc_vw_fun_info");
                v_dtbSide = EXECUTE_CMD_ORACLE("Select cdval KeyName, cdcontent KeyValue From ALLCODE where cdname='BORS' and cdtype='FA'");

                //cl_u.Set_value_to_Combobox(cl_u.v_dtbSymbolInfo, this.cbb_MH1_Symbol_in, "KeyName", "");
                cl_u.FILL_HashTable(cl_u.v_HtbCompanyLIst, v_dtbCompanyInFoFind, this.cbb_Company_Name, "");
                //cl_u.FILL_HashTable(cl_u.v_HtbSymbol, cl_u.v_dtbSymbolInfo, null);
                cl_u.FILL_HashTable(cl_u.v_HtbSymbol, cl_u.v_dtbSymbolInfo, this.cbb_MH1_Symbol_in, "KEY");
                cl_u.FILL_HashTable(cl_u.v_HtbSubfund, v_dtbSubFundInfo, this.cbb_SUbFund, "");
                cl_u.FILL_HashTable(v_HtbSide, v_dtbSide, this.Cbb_MH1_Side_Loai_lenh, "");
                Tim_kiem_theo_dieu_kien(true);
                checkBox_Tim_kiem_nang_cao.Checked = false;
                this.Set_value_to_Combobox(v_dtbCompanyInFoFull, this.cbb_SubFundName, "subfundname", "");
                this.cbb_SubFundName.Items.Add("");
                this.cbb_SubFundName.SelectedIndex = this.cbb_SubFundName.Items.Count - 1;
                cl_u.Set_value_to_Combobox(cl_u.v_dtbSymbolInfo, this.cbb_SymBol, "KeyName", "");
                this.LoadTabPhongVT();
            }
            catch (Exception ex)
            {
                _code._services.UPDATE_LOG_FILE("ERR", Code.StaticVariable.userID, "Load form màn hình phân bổ lệnh", "Form1_Load", ex.ToString());
                Log_ung_dung(ex.ToString());
            }
          
        }

        private void Cbb_MH1_Side_Loai_lenh_TextChanged(object sender, EventArgs e)
        {
            REFRESH_ORG_ORDER();
        }

        private void cbb_MH1_Symbol_in_TextChanged(object sender, EventArgs e)
        {
            string v_strSymbol = cbb_MH1_Symbol_in.Text;
            // han che viec load khi danh danh ma chung khoan
            if (v_strSymbol.Length >= 3)
            {
                load_thong_tin_chung_khoan(cbb_MH1_Symbol_in.Text);
                REFRESH_ORG_ORDER();
            }
        }

        private void cbb_MH1_gia_dat_du_kien_TextChanged(object sender, EventArgs e)
        {
            //CALCULATE_ALOCATE_ORDER("CAL");
        }

        private void cbb_MH1_KL_Du_kien_TextChanged(object sender, EventArgs e)
        {
            CALCULATE_ALOCATE_ORDER("CAL");
        }

        private void radioButton_PhanBo_Lenh_CheckedChanged(object sender, EventArgs e)
        {
            RECALCULATE_ALOCATE_ORDER("CAL");
        }

        private void dataGridView1_CellMouseDown(object sender, DataGridViewCellMouseEventArgs e)
        {
            v_SubFunName = "";
            try
            {
                DataGridViewCell clickedCell = (sender as DataGridView).Rows[e.RowIndex].Cells[e.ColumnIndex];
                this.dataGridView1.CurrentCell = clickedCell;
                int v_CurrentRow = clickedCell.RowIndex;

                //v_CompanyName = dataGridView1.Rows[v_CurrentRow].Cells["COMPANYNAME"].Value.ToString();
                //v_FundName = dataGridView1.Rows[v_CurrentRow].Cells["FUNDNAME"].Value.ToString();
                v_SubFunName = dataGridView1.Rows[v_CurrentRow].Cells["SUBFUNDNAME"].Value.ToString();
                v_Custodycd = dataGridView1.Rows[v_CurrentRow].Cells["CUSTODYCD"].Value.ToString();
                V_unOrderQTY = dataGridView1.Rows[v_CurrentRow].Cells["UNORDERED QUANTITY"].Value.ToString();
                v_Side = dataGridView1.Rows[v_CurrentRow].Cells["B/S"].Value.ToString();
                V_Symbol = dataGridView1.Rows[v_CurrentRow].Cells["Ticker"].Value.ToString();
                V_LimitQuantity = dataGridView1.Rows[v_CurrentRow].Cells["Amt"].Value.ToString();
                v_LimitPrice = dataGridView1.Rows[v_CurrentRow].Cells["Limit price ('000vnd)"].Value.ToString();
                //if (e.RowIndex != -1 && e.ColumnIndex != -1)
                //{
                //    if (e.Button == MouseButtons.Right)
                //    {
                //        var relativeMousePosition = dataGridView1.PointToClient(Cursor.Position);
                //        //this.contextMenuStrip_Huy_lenh_chi_thi.Show(dataGridView1, relativeMousePosition);
                //    }
                //}
            }
            catch (Exception ex)
            {
                _code._services.UPDATE_LOG_FILE("ERR", Code.StaticVariable.userID, "nhay chuot phai chon menu sua lenh chi thi", "dataGridView1_CellMouseDown", ex.ToString());
                Log_ung_dung(ex.ToString());
            }
        }

        private void toolStripMenuItem1_Them_moi_lenh_chi_thi_Click(object sender, EventArgs e)
        {
            try
            {
                Frm_Orgorder_manage frm_orgOrder = new Frm_Orgorder_manage(cl_u.v_HtbSubfund, cl_u.v_HtbSymbol, cl_u.v_dtbSymbolInfo);
                frm_orgOrder.Get_FormType = "ADD";
                frm_orgOrder.Get_dtbCompanyInfo = v_dtbCompanyInFoFull;
                frm_orgOrder.ShowDialog();
            }
            catch { }
        }

        private void toolStripMenuItem1_Sua_lenh_chi_thi_Click(object sender, EventArgs e)
        {
            try
            {
                if (v_SubFunName.Trim() == "")
                {
                    MessageBox.Show("Chọn lệnh chỉ thị cần sửa", "Thông báo");
                    return;
                }
                Frm_Orgorder_manage frm_orgOrder = new Frm_Orgorder_manage(cl_u.v_HtbSubfund, cl_u.v_HtbSymbol, cl_u.v_dtbSymbolInfo);
                frm_orgOrder.Get_dtbCompanyInfo = v_dtbCompanyInFoFull;
                frm_orgOrder.Get_FormType = "EDIT";
                frm_orgOrder.Get_CompanyName = v_CompanyName;
                frm_orgOrder.Get_FundName = v_FundName;
                frm_orgOrder.Get_SubFunName = v_SubFunName;
                frm_orgOrder.Get_Custodycd = v_Custodycd;
                frm_orgOrder.Get_Side = v_Side;
                frm_orgOrder.Get_Symbol = V_Symbol;
                frm_orgOrder.Get_LimitQuantity = V_LimitQuantity;
                frm_orgOrder.Get_LimitPrice = v_LimitPrice;
                frm_orgOrder.ShowDialog();
            }
            catch { }
        }

        private void toolStripMenuItem_Huy_lenh_chi_Thi_Click(object sender, EventArgs e)
        {
            try
            {
                if (v_SubFunName.Trim() == "")
                {
                    MessageBox.Show("Chọn lệnh chỉ thị cần hủy", "Thông báo");
                    return;
                }

                if (V_LimitQuantity != V_unOrderQTY)
                {
                    MessageBox.Show("Không thể hủy lệnh đã được phân bổ ! ", "Thông báo");
                    return;
                }

                Frm_Orgorder_manage frm_orgOrder = new Frm_Orgorder_manage(cl_u.v_HtbSubfund, cl_u.v_HtbSymbol, cl_u.v_dtbSymbolInfo);
                frm_orgOrder.Get_dtbCompanyInfo = v_dtbCompanyInFoFull;
                frm_orgOrder.Get_FormType = "DELT";
                frm_orgOrder.Get_CompanyName = v_CompanyName;
                frm_orgOrder.Get_FundName = v_FundName;
                frm_orgOrder.Get_SubFunName = v_SubFunName;
                frm_orgOrder.Get_Custodycd = v_Custodycd;
                frm_orgOrder.Get_Side = v_Side;
                frm_orgOrder.Get_Symbol = V_Symbol;
                frm_orgOrder.Get_LimitQuantity = V_LimitQuantity;
                frm_orgOrder.Get_LimitPrice = v_LimitPrice;
                frm_orgOrder.ShowDialog();

            }
            catch { }
        }

        private void btn_Lam_moi_TTPBL_Click(object sender, EventArgs e)
        {
            //RECALCULATE_ALOCATE_ORDER("CAL");
            panel1_mua_ban.BackColor = Color.DarkKhaki;
            this.lbl_MCK.Text = "";
            //lbl_San_giao_dich.Text = "";
            lbl_Gia_san.Text = "";
            lbl_Tham_chieu.Text = "";
            lbl_Gia_tran.Text = "";
            this.cbb_MH1_gia_dat_du_kien.Text = "";
            this.cbb_MH1_KL_Du_kien.Text = "";
            dataGridView2_lenh_Phan_bo.DataSource = null;
        }

        private void cbb_Company_Name_SelectedIndexChanged(object sender, EventArgs e)
        {
            REFRESH_ORG_ORDER();
        }

        private void cbb_phongvt_sotk_SelectedIndexChanged(object sender, EventArgs e)
        {
            LoadTTTienNongVaCK();
        }

        // Khi bam nut Edit, Cancel ben trái gridview 
        private void gridview_LenhChiThi_TQ_CellContentClick(object sender, DataGridViewCellEventArgs e)
        {
            var senderGrid = (DataGridView)sender;
            if (senderGrid.Columns[e.ColumnIndex] is DataGridViewButtonColumn && e.RowIndex >= 0)
            {
                DataGridViewButtonCell btn = gridview_LenhChiThi_TQ.Rows[e.RowIndex].Cells[e.ColumnIndex] as DataGridViewButtonCell;
                v_SubFunName = gridview_LenhChiThi_TQ.Rows[e.RowIndex].Cells["SUBFUNDNAME"].Value.ToString();
                v_Custodycd = gridview_LenhChiThi_TQ.Rows[e.RowIndex].Cells["CUSTODYCD"].Value.ToString();
                V_unOrderQTY = gridview_LenhChiThi_TQ.Rows[e.RowIndex].Cells["UNORDERED QUANTITY"].Value.ToString();
                v_Side = gridview_LenhChiThi_TQ.Rows[e.RowIndex].Cells["B/S"].Value.ToString();
                V_Symbol = gridview_LenhChiThi_TQ.Rows[e.RowIndex].Cells["Ticker"].Value.ToString();
                if (V_Symbol.Contains(" *"))
                {
                    V_Symbol = V_Symbol.Remove(3, 2);
                }
                V_LimitQuantity = gridview_LenhChiThi_TQ.Rows[e.RowIndex].Cells["Amt"].Value.ToString();
                v_LimitPrice = gridview_LenhChiThi_TQ.Rows[e.RowIndex].Cells["Limit price ('000vnd)"].Value.ToString();

                Frm_Orgorder_manage frm_orgOrder = new Frm_Orgorder_manage(cl_u.v_HtbSubfund, cl_u.v_HtbSymbol, cl_u.v_dtbSymbolInfo);
                frm_orgOrder.Get_dtbCompanyInfo = v_dtbCompanyInFoFull;
                frm_orgOrder.Get_CompanyName = v_CompanyName;
                frm_orgOrder.Get_FundName = v_FundName;
                frm_orgOrder.Get_SubFunName = v_SubFunName;
                frm_orgOrder.Get_Custodycd = v_Custodycd;
                frm_orgOrder.Get_Side = v_Side;
                frm_orgOrder.Get_Symbol = V_Symbol;
                frm_orgOrder.Get_LimitQuantity = V_LimitQuantity;
                frm_orgOrder.Get_LimitPrice = v_LimitPrice;

                if (btn.Value.ToString().Equals("Edit"))
                {
                    try
                    {
                        frm_orgOrder.Get_FormType = "EDIT";
                        frm_orgOrder.ShowDialog();
                        LoadTabPhongVT();
                        LoadTTTienNongVaCK();
                        return;
                    }
                    catch { }
                }
                if (btn.Value.ToString().Equals("Cancel"))
                {
                    try
                    {
                        frm_orgOrder.Get_FormType = "DELT";
                        frm_orgOrder.ShowDialog();
                        LoadTabPhongVT();
                        LoadTTTienNongVaCK();
                        return;
                    }
                    catch { }
                }
            }
        }

        private void btnConfirm_Click(object sender, EventArgs e)
        {
            this.Order_Click(this._BtnConfirmType, "ADD");
            this.cbb_SubFundName.SelectedIndex = this.cbb_SubFundName.Items.Count - 1;
            this.cbb_SymBol.Text = "";
            this.cbb_LimitQuantty.Text = "";
            this.cbb_LimitPrice.Text = "";
            this._BtnConfirmType = "";
            this.panel2.BackColor = Color.White;
        }

        private void gridView4_RowCellStyle(object sender, DevExpress.XtraGrid.Views.Grid.RowCellStyleEventArgs e)
        {
            DevExpress.XtraGrid.Views.Grid.GridView view = sender as DevExpress.XtraGrid.Views.Grid.GridView;
            if (view.GetDataRow(e.RowHandle) != null)
            {
                DataRow drIsValid = view.GetDataRow(e.RowHandle);
                if (drIsValid["B/S"].ToString() == "B")
                {
                    e.Appearance.ForeColor = System.Drawing.Color.Green;
                }
                else
                {
                    e.Appearance.ForeColor = System.Drawing.Color.Red;
                }

                // Bold dong lenh chi thi goc
                try
                {
                    for (int i = 0; i < gridView4.RowCount; i++)
                    {
                        if (Convert.ToDouble(drIsValid["AUTOID"]) == this._minAutoID)
                        {
                            e.Appearance.Font = new Font(gridview_instruction_order_hist.Font, FontStyle.Bold);
                        }
                    }
                }
                catch (Exception ex) { }

                // neu chi co 1 thi bold luon
                if (gridView4.RowCount == 1)
                {
                    e.Appearance.Font = new Font(gridview_instruction_order_hist.Font, FontStyle.Bold);
                }

                // neu ALL thi hien thi het, Bold tat ca lenh goc
                if (this._minAutoIDs_check == true)
                {
                    for (int i = 0; i < this._minAutoIDs.Count; i++)
                    {
                        if (Convert.ToString(drIsValid["autoid"]) == this._minAutoIDs[i])
                        {
                            e.Appearance.Font = new Font(gridview_instruction_order_hist.Font, FontStyle.Bold);
                        }
                    }
                }
            }
        }

        //Load lich su bsc_fao_instruction_order_hist
        private void gridview_LenhChiThi_TQ_CellDoubleClick(object sender, DataGridViewCellEventArgs e)
        {
            if (e != null)
            {
                this._orderID_Hist = Convert.ToString(this.gridview_LenhChiThi_TQ.SelectedRows[0].Cells["insorderid"].Value);
            }

            DataTable _tmp = new DataTable("noname");
            _tmp = this.EXECUTE_CMD_ORACLE("select to_char( i.txtime, 'HH24:MI:SS' ) as \"Time\", sf.subfundname, f.custodycd , i.side as \"B/S\",i.symbol,i.Limitprice / 1000 as \"Limit price ('000vnd)\", TO_CHAR( i.limitqty, '999,999,999,999,999,999,999') as \"Limitquantity\" ,i.insorderid ,i.autoid " +
                                            "from bsc_fao_instruction_order_hist i, bsc_fao_subfunds_info sf , bsc_fao_funds_info f " +
                                            "where i.txdate=getcurrdate " +
                                            "and i.subfundid = sf.subfundid " +
                                            "and sf.fundid = f.fundid " +
                                            "and i.insorderid like '" + this._orderID_Hist + "' " +
                                            "order by txtime desc");
            if (_tmp.Rows.Count == 0)
            {
                _tmp = this.EXECUTE_CMD_ORACLE("select to_char( i.last_change, 'HH24:MI:SS' ) as \"Time\" , sf.subfundname, f.custodycd, i.side as \"B/S\" , i.symbol, i.Limitprice / 1000 as \"Limit price ('000vnd)\",TO_CHAR( i.limitqty, '999,999,999,999,999,999,999') as \"Limitquantity\", i.insorderid ,NULL as AUTOID " +
                                                        " from bsc_fao_instruction_order i , bsc_fao_subfunds_info sf , bsc_fao_funds_info f " +
                                                        " where insorderid like '" + this._orderID_Hist + "' " +
                                                        " and sf.subfundid = i.subfundid" +
                                                        " and sf.fundid = f.fundid "+
                                                        " and i.txdate=getcurrdate ");

            }
            this.gridview_instruction_order_hist.DataSource = _tmp;

            try
            {
                this._minAutoID = 99999;
                foreach (DataRow row in _tmp.Rows)
                {
                    if (this._minAutoID > Convert.ToDouble(row["AUTOID"]))
                    {
                        this._minAutoID = Convert.ToDouble(row["AUTOID"]);
                    }
                }
            }
            catch (Exception ex) { }

            // sua lai width 1 so cot
            this.gridView4.Columns["AUTOID"].Width = 50;
            this.gridView4.Columns["INSORDERID"].Width = 70;
            this.gridView4.Columns["SUBFUNDNAME"].Width = 300;
            this.gridView4.Columns["B/S"].Width = 50;

            // can le phai 1 so cot
            this.gridView4.Columns["Limitquantity"].AppearanceCell.TextOptions.HAlignment = DevExpress.Utils.HorzAlignment.Far;
        }

        private void btnRefreshViewLenhChiThi_Hist_Click(object sender, EventArgs e)
        {
            this._orderID_Hist = "%%";
            DataTable _tmpMinAutoIDs = this.EXECUTE_CMD_ORACLE("select min(autoid) as min_id from bsc_fao_instruction_order_hist " +
                                                                   " where txdate = getcurrdate " +
                                                                   " group by insorderid");
            this._minAutoIDs.Clear();
            foreach (DataRow row in _tmpMinAutoIDs.Rows)
            {
                this._minAutoIDs.Add(Convert.ToString(row["min_id"]));
            }
            this._minAutoIDs_check = true;
            this.gridview_LenhChiThi_TQ_CellDoubleClick(sender, null);
        }

        private void đãXácNhậnToolStripMenuItem_Click(object sender, EventArgs e)
        {
            if (this.toadoX != 0 && this.toadoX != 1 && this.toadoY == 0)
            {
                string tien = this.gridviewTien_Phongvt.Rows[0].Cells[this.toadoX].Value.ToString();
                string subfundid = "";
                foreach (DataRow row in this.v_dtbCompanyInFoFull.Rows)
                {
                    if (Convert.ToString(row["subfundname"]) == this.gridviewTien_Phongvt.Columns[this.toadoX].HeaderText)
                    {
                        subfundid = Convert.ToString(row["subfundid"]);
                    }
                }
                this.EXECUTE_CMD_ORACLE("update bsc_tbl_confirm_nhlk set checktien='1' where txdate=getcurrdate and subfundid='" + subfundid + "'");
                LoadTTTienNongVaCK();
            }
        }

        private void gridviewTien_Phongvt_MouseDown(object sender, MouseEventArgs e)
        {
            if (e.Button == MouseButtons.Right)
            {
                var hti = gridviewTien_Phongvt.HitTest(e.X, e.Y);
                this.toadoX = hti.ColumnIndex;
                this.toadoY = hti.RowIndex;
            }
        }

        private void btnRefresh_ManHinhXacNhanSoDu_Click(object sender, EventArgs e)
        {
            this.LoadTTTienNongVaCK();
        }

        private void btn_SolenhHome_CanCel_Click(object sender, EventArgs e)
        {
            try
            {
                GetSelectedDataRows();
                if (_tableHuyLenh.Rows.Count > 0)
                {
                    Frm_CancelOrder frm_CancelOrder = new Frm_CancelOrder();
                    frm_CancelOrder.Get_LenhHuy = _tableHuyLenh;
                    frm_CancelOrder.ShowDialog();
                    REFRESH_ORG_ORDER();
                    Tim_kiem_theo_dieu_kien(true);
                }
                else
                {
                    MessageBox.Show("Không tìm thấy thông tin lệnh cần hủy", "Thông báo");
                }
            }

            catch (Exception ex)
            {
                _code._services.UPDATE_LOG_FILE("ERR", Code.StaticVariable.userID, "HuyLenhToolStripMenuItem_Click", "HuyLenhToolStripMenuItem_Click", ex.ToString());
                Log_ung_dung(ex.ToString());
            }
        }

        private void SuaLenhToolStripMenuItem_Click(object sender, EventArgs e)
        {
            DataRow rowSelect = this.gridView1.GetFocusedDataRow();
            string v_gia = cl_u.Get_value_HashTable(cl_u.v_HtbSymbol, Convert.ToString(rowSelect["symbol"]));
            string[] v_arrGia = v_gia.Split('|');
            Frm_Edit_Order _form = new Frm_Edit_Order(Convert.ToString(rowSelect["CUSTID"]), Convert.ToString(rowSelect["custodycd"]), Convert.ToString(rowSelect["exectype"]),
                                                      Convert.ToString(rowSelect["symbol"]), Convert.ToString(rowSelect["QUOTEPRICE"]),
                                                      Convert.ToString(rowSelect["ORDERQTTY"]), Convert.ToString(rowSelect["TRADEPLACE"]),
                                                      Convert.ToString(rowSelect["orgorderid"]), v_arrGia[1], v_arrGia[3]);
            _form.ShowDialog();
        }

        #endregion

        private void cbbSolanKLToiDa_SelectedIndexChanged(object sender, EventArgs e)
        {
            if (this.cbbSolanKLToiDa.Text == "")
            {
                MessageBox.Show("Bạn chưa chọn số lần lặp lệnh!");
                this.cbbSolanKLToiDa.Focus();
            }
            else
            {
                int solan = Convert.ToInt32(this.cbbSolanKLToiDa.Text);
                this.dtb_tep2.Rows.Clear();
                for (int i = 0; i < solan; i++)
                {
                    DataTable tmp = EXECUTE_PROCEDURE_ORACLE("FAO003", this.btc_CompanyID, this.btc_Side, this.btc_Symbol, Convert.ToDouble(this.cbb_MH1_gia_dat_du_kien.Text), this.btc_Quantity);
                    foreach (DataRow row in tmp.Rows)
                    {
                        this.dtb_tep2.ImportRow(row);
                    }
                }
                this.dataGridView2_lenh_Phan_bo.DataSource = null;
                this.dataGridView2_lenh_Phan_bo.DataSource = dtb_tep2;

                // hien thi KL dang dat
                this.lbl_KL_DangDat.Text = "";
                this.lbl_KL_DangDat.Text += Convert.ToString(solan * Convert.ToDouble(cbb_MH1_KL_Du_kien.Text));

                double tongKL = 0;
                foreach (DataGridViewRow row in this.dataGridView1.Rows)
                {
                    tongKL += Convert.ToDouble(row.Cells["Amt"].Value);
                }
                this.lbl_KL_Tong_x.Text = "";
                this.lbl_KL_Tong_x.Text += tongKL;
            }
        }

        private void btnRefresh_SoLenhHome_Click(object sender, EventArgs e)
        {
            DataTable result = new DataTable("noname");
            DataTable tableValue = new DataTable("value");

            // tao 6 cot
            tableValue.Columns.Add("P_TXDATE");
            tableValue.Columns.Add("P_TLID");
            tableValue.Columns.Add("P_CUSTODYCD");
            tableValue.Columns.Add("P_AFACCTNO");
            tableValue.Columns.Add("P_EXECTYPE");
            tableValue.Columns.Add("P_SYMBOL");
            tableValue.Columns.Add("P_FULLNAME");

            // tao 1 Row chua gia tri
            DataRow rowValue = tableValue.NewRow();
            rowValue["P_TXDATE"] = "0";
            rowValue["P_TLID"] = "1004";
            rowValue["P_CUSTODYCD"] = "";
            rowValue["P_FULLNAME"] = this.cbb_Company_Name.Text;
            rowValue["P_AFACCTNO"] = "%%";
            rowValue["P_EXECTYPE"] = "%%";
            rowValue["P_SYMBOL"] = "%%";
            tableValue.Rows.Add(rowValue);

            // tao 1 Row chua kieu Du lieu cua cot ( int, string ?? ...)
            DataRow rowDataType = tableValue.NewRow();
            rowDataType["P_TXDATE"] = "T";
            rowDataType["P_TLID"] = "T";
            rowDataType["P_CUSTODYCD"] = "T";
            rowDataType["P_FULLNAME"] = "T";
            rowDataType["P_AFACCTNO"] = "T";
            rowDataType["P_EXECTYPE"] = "T";
            rowDataType["P_SYMBOL"] = "T"; 
            tableValue.Rows.Add(rowDataType);

            result = _code._services.Excute_Store_By_ListString("fa_api.sp_get_order_by_careby", tableValue);
            this.gridControl_SoLenhHOME.DataSource = null;
            this.gridControl_SoLenhHOME.DataSource = this.ThayTenCot_SoLenhHome(result); 
        }
    }
}
